Hi! Something has been puzzling me for a while and...
# android
p
Hi! Something has been puzzling me for a while and I could not get a good explanation online On Android we cannot do network operations on the main thread, however with coroutines, why does this work?
Copy code
viewModelScope.launch(Dispatchers.Main) {
    Log.d("Test", "Current thread is: ${Thread.currentThread().name}")
    
    doSomeNetworkCall()
}
The log effectively prints:
Current thread is: main
I was expecting my app to blow up 🤔
k
Retrofit switches to an IO dispatcher in their suspend methods.
😮 1
💯 1
p
I see! Thanks for the quick reply ❤️
m
The general guideline is that suspend functions should be main thread safe. So if a suspend function is going to block the thread instead of just suspending, it needs to get off the main thread. Retrofit and most other libraries that provide coroutine friendly IO obey this. But in general it is the responsibility of the function to switch dispatchers when needed and not the caller.
💯 5
p
Yep agreed. I now remember reading about these good practices when writing coroutine code