A coroutine runs on whatever thread its dispatcher gives it, and the dispatcher is part of the coroutine context. Picking the wrong one is the most common cause of a frozen Android screen.
Four matter. Dispatchers.Main is the single UI thread - every touch event and every pixel drawn goes through it, so anything slow here freezes the app. Dispatchers.IO is a large elastic pool sized for work that spends its time waiting, such as network calls, disk reads and database queries. Dispatchers.Default is sized to the number of CPU cores and is for work that burns CPU, such as parsing, sorting or image processing. Dispatchers.Unconfined resumes wherever the previous suspension left it and is for library internals and tests, not application code.
The rule is simple to state. Waiting goes on IO, computing goes on Default, touching the UI goes on Main. Over-sizing IO is deliberate - a thread blocked on a socket is not using a core, so a pool of sixty-four is reasonable there and catastrophic for CPU work.
withContext switches dispatcher for a block and switches back when it finishes. The idiomatic pattern is for a suspend function to be main-safe: it moves to the right dispatcher internally, so a caller can invoke it from anywhere without thinking. A function that requires the caller to wrap it is a leaky API.
import kotlinx.coroutines.*
// Main-safe: the caller never has to know which dispatcher this needs
suspend fun loadAndParse(url: String): Int {
val raw = withContext(Dispatchers.IO) {
// Waiting on a socket - belongs on the elastic pool
delay(200)
"1,2,3,4,5"
}
return withContext(Dispatchers.Default) {
// Burning CPU - belongs on the core-sized pool
raw.split(",").sumOf { it.trim().toInt() }
}
}
fun main() = runBlocking {
println(loadAndParse("https://example.com")) // 15
// Naming a coroutine makes a stack trace readable
launch(Dispatchers.Default + CoroutineName("worker")) {
println("running as ${coroutineContext[CoroutineName]?.name}")
}.join()
}
Discussion
No questions on this topic yet. Sign in to ask the first one.