Concept Flow - Dispatchers.Main, IO, Default behavior
Start Coroutine
Choose Dispatcher
Main
Run on UI
Complete Coroutine
When a coroutine starts, it picks a dispatcher: Main for UI tasks, IO for input/output, Default for CPU work.
launch(Dispatchers.Main) {
println("Running on Main")
}
launch(Dispatchers.IO) {
println("Running on IO")
}
launch(Dispatchers.Default) {
println("Running on Default")
}| Step | Coroutine | Dispatcher | Thread Type | Action | Output |
|---|---|---|---|---|---|
| 1 | Coroutine 1 | Dispatchers.Main | Main/UI Thread | Start coroutine on UI thread | Running on Main |
| 2 | Coroutine 2 | Dispatchers.IO | IO Thread Pool | Start coroutine on IO thread | Running on IO |
| 3 | Coroutine 3 | Dispatchers.Default | CPU Thread Pool | Start coroutine on CPU thread | Running on Default |
| 4 | All | - | - | Coroutines complete | - |
| Coroutine | Dispatcher | Thread Type | Status |
|---|---|---|---|
| Coroutine 1 | Dispatchers.Main | Main/UI Thread | Completed |
| Coroutine 2 | Dispatchers.IO | IO Thread Pool | Completed |
| Coroutine 3 | Dispatchers.Default | CPU Thread Pool | Completed |
Dispatchers.Main runs coroutines on the UI thread for UI updates. Dispatchers.IO is for blocking IO tasks using a thread pool. Dispatchers.Default handles CPU-intensive work on background threads. Choose dispatcher based on task type to keep app responsive. Coroutines complete after running on their assigned threads.
Dispatcher should you use in Kotlin when updating the user interface (UI)?Dispatchers.Main is designed for UI tasks on the main thread.CoroutineScope(Dispatchers.IO).launch { ... } is correct syntax for IO dispatcher.import kotlinx.coroutines.*
fun main() = runBlocking {
launch(Dispatchers.Default) {
println("Running on: " + Thread.currentThread().name)
}.join()
}Dispatchers.Default, which uses a shared background thread pool.CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
// Perform file read
}
println("File read complete")
}
What is the main issue if this code is run in an Android app?Select the best option.
Dispatchers.Default is designed for CPU-heavy tasks using a shared thread pool.Pass the test and this pattern moves unknown