lawlorslaw
05/12/2022, 7:17 PMexchangeRepository.getExchanges()
is the call to the suspend
function.Jorge Domínguez
05/12/2022, 7:20 PMviewModelScope
runs by default on Dispatchers.Main
, so it does run on the main thread. If you want to move the execution context to a background thread you could use withContext()
Casey Brooks
05/12/2022, 7:21 PMviewModelScope
uses the Dispatchers.Main.immediate
dispatcher by default, but this is actually how it should be set up, preferably. The “structured concurrency” expectation is that if any given suspend
method needs to be executed on a different dispatcher, that it should move itself there, rather than requiring the callers to be on the proper dispatcher.
So make sure the API call is done on <http://Dispatchers.IO|Dispatchers.IO>
internally by wrapping its implementation with withContext(<http://Dispatchers.IO|Dispatchers.IO>)
, and you shouldn’t have to worry about changing dispatchers for it in the ViewModellawlorslaw
05/12/2022, 7:24 PMlawlorslaw
05/12/2022, 7:26 PMJorge Domínguez
05/12/2022, 7:26 PMExchangeRepository {
suspend fun getExchange(...) = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
....
}
}
lawlorslaw
05/12/2022, 7:27 PMlawlorslaw
05/12/2022, 7:27 PMlawlorslaw
05/12/2022, 7:27 PMCasey Brooks
05/12/2022, 7:27 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
in your Repository, not the ViewModel.
class ExchangeRepository {
suspend fun getExchange() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
// ...
}
}
lawlorslaw
05/12/2022, 7:27 PMlawlorslaw
05/12/2022, 7:27 PMlawlorslaw
05/12/2022, 7:29 PMlawlorslaw
05/12/2022, 7:29 PMJorge Domínguez
05/12/2022, 7:30 PMclass ExchangeRepository(
private val dispatcher: CoroutineDispatcher = <http://Dispatchers.IO|Dispatchers.IO>
) {
suspend fun getExchange() = withContext(dispatcher) {
...
}
}
Casey Brooks
05/12/2022, 7:31 PMlawlorslaw
05/12/2022, 7:31 PMreturn
keywordlawlorslaw
05/12/2022, 7:31 PMlawlorslaw
05/12/2022, 7:31 PMephemient
05/13/2022, 12:11 AMreturn@withContext
if you want to be explicit