Dispatchers
- Kotlin course
- Advanced
- Lesson 2/83
- 5 min
Learn contexts with Dispatchers.IO, Default and Main.
What are Dispatchers?
Dispatchers decide which thread pool a coroutine runs on. Dispatchers.IO is for network and disk, Dispatchers.Default for CPU heavy work, and Dispatchers.Main for the UI thread.
You pass a dispatcher when starting a coroutine: launch(Dispatchers.IO) { ... }. You can switch a running coroutine's dispatcher temporarily with withContext. Choosing the right dispatcher matters for performance.
IO vs Default vs Main
Dispatchers.IO is a pool that can grow up to 64 threads; it is ideal for waiting work like network and files. Dispatchers.Default offers as many threads as CPU cores; it suits computation.
Dispatchers.Main is platform specific; on Android it is the UI thread. UI updates happen here. With withContext(Dispatchers.Default) { ... } you move CPU work to Default temporarily, then return to Main. A wrong dispatcher freezes the UI.
Practice Switch dispatcher with withContext
Inside runBlocking, open a block with withContext(Dispatchers.Default). Print println("Computed") inside it. After the block, print println("Done").
Starter code
// Switch dispatcher with withContext
// write here
fun main() = runBlocking {
}Sample solution
fun main() = runBlocking {
withContext(Dispatchers.Default) {
println("Computed")
}
println("Done")
}Expected output
Computed Done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pick the dispatcher for a network call
launch(Dispatchers.____) { fetchUsers() }
launch(Dispatchers.IO) { fetchUsers() }
Explanation: Dispatchers.IO is used for network and disk.
2 Match dispatchers to their use
| Term | Meaning |
|---|---|
Dispatchers.IO |
Network and disk |
Dispatchers.Default |
CPU heavy work |
Dispatchers.Main |
UI thread |
withContext |
Temporary switch |
3 Which dispatcher should run a CPU heavy computation?
- Dispatchers.Main
- Dispatchers.Default Correct answer
- Dispatchers.IO
- Dispatchers.Unconfined
Explanation: CPU work runs on Dispatchers.Default.