https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

voben

04/23/2020, 3:52 PM
How do you know when to switch to another dispatcher? On android, when performing a network request within a viewModel scope, my understanding okhttp will perform the fetching task on a background thread. So when I get the response, and want to massage the data before sending to the UI, is this work ok for the main thread? Or do I need to switch to another Dispatcher at this point?
Copy code
viewModelScope.launch {
   val myResponse = fetchMyData() // okhttp moves this work to a background thread
   doSomethingWithMyResponse(myResponse) // Does this need to be done on a background thread using withContext?
}
d

Dominaezzz

04/23/2020, 4:00 PM
Since okhttp does threading in a different thread, you don't have to switch to
<http://Dispatcher.IO|Dispatcher.IO>
, the main thread will suffice.
You only need to worry about switching dispatchers if the library/code you're calling does blocking calls synchronously.
o

octylFractal

04/23/2020, 5:03 PM
note that unless you're using okhttp's async api, it is blocking, but it's quite easy to adapt it using
suspendCancellableCoroutine
11 Views