Just learning coroutines (on Android in this examp...
# coroutines
c
Just learning coroutines (on Android in this example). I was expecting this to hang my app (ANR) because I didn't select a scheduler/dispatcher/thread/whateverItsCalledInKotlin
Copy code
fun 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?
o
viewModelScope
inherently contains the
Dispatcher.Main
element
there is not an easy way to tell when a suspend function will run on a different thread in terms of reading the code, but if you wanted to check at runtime you could always check if the dispatcher is changing. as a note,
launch
,
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
t
Well designed suspending functions should only suspend the caller and not execute blocking code. Which means that calling
delay(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>)
.
1
b
For Retrofit, it will use its scheduler, so you don't need to switch over to an IO thread. It hugely depends. On Android, it's pretty common for things to be "main thread safe" (ie, retrofit, room, etc)
g
Suspend function should be always implemented in a "main thread safe" way, otherwise it's incorrect implementation, it makes a lot harder to use them when you not sure that it's safe to use in asynchronous code
Your example above uses delay which is non-blocking suspend function, so it's also safe to use, it's not just "block current thread for 10 seconds"