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

Colton Idle

12/09/2019, 8:00 AM
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

octylFractal

12/09/2019, 8:01 AM
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

tseisel

12/09/2019, 9:02 AM
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

bdawg.io

12/09/2019, 10:28 AM
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

gildor

12/09/2019, 12:45 PM
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"
2 Views