viewModelScope explanation misleading

Example code being referenced:

viewModelScope.launch {
    delay(5000)
    ...
}

Page 233 states:

Because delay is running inside a coroutine, during the five seconds that the function is counting milliseconds your UI is still capable of drawing any new updates and can instantly respond to user input

I think it might be beneficial to explain the nuance of the fact that viewModelScope.launch is executing on the main thread, and the only reason the UI isn’t blocked is because we are calling a suspend fun (delay) that itself dispatches off the main thread. The quoted explanation above makes it sound as though any arbitrary blocking code could be added inside viewModelScope.launch without blocking the UI.

References:
[1] android - Does block inside viewmodelscope runs on Main thread or background thread? - Stack Overflow
[2] Các phương pháp hay nhất cho coroutine trong Android  |  Kotlin  |  Android Developers

3 Likes

Thank you for calling this out. You are 100% correct. Coroutines allow you to easily write asynchronous code, but by default, the code in a coroutine scope executes on the thread in which it was invoked. delay() is just smart enough to let other code execute while it is waiting. Not all async code is like that though. Also, some code is asynchronous because it is actually doing a ton of work. In that case, that ton of work would happen on the main thread, which would prevent the OS from drawing your UI for you, resulting in a laggy UI. Any heavy computation or I/O in a coroutine should be performed on a background thread, so that the main thread can be freed up to draw the UI.