Colton Idle
12/09/2019, 8:00 AMfun buttonClick() {
viewModelScope.launch {
delay(10000)
_myPrivateData.value = "Two"
}
}
Is there an easy way to tell when a suspend function will run on a different thread? For example, I will be using coroutines with Retrofit and at first it seems like I would have to tell it to run on a different thread, but it seems like I won't have to do that from the tutorials I've read?octylFractal
12/09/2019, 8:01 AMviewModelScope
inherently contains the Dispatcher.Main
elementoctylFractal
12/09/2019, 8:04 AMlaunch
, async
-- all of the CoroutineScope
functions -- spawn a separate task that doesn't block the current thread unless you're using Dispatcher.Main.immediate
, Dispatcher.Undispatched
, or CoroutineStart.UNDISPATCHED
tseisel
12/09/2019, 9:02 AMdelay(10000)
(or any other suspend fun) should never trigger the ANR, since the Main Thread is not blocked.
In the special case of Retrofit, when marking the interface function with the suspend
modifier, Retrofit will suspend the caller and execute the request on a background thread by itself. This way you won't fail with a NetworkOnMainThread
and you won't need withContext(<http://Dispatchers.IO|Dispatchers.IO>)
.bdawg.io
12/09/2019, 10:28 AMgildor
12/09/2019, 12:45 PMgildor
12/09/2019, 12:48 PM