Dispatchers help your program decide where to run tasks. This keeps your app smooth and fast by running work in the right place.
0
0
Dispatchers.Main, IO, Default behavior in Kotlin
Introduction
When you want to update the screen or user interface.
When you need to read or write files or talk to the internet.
When you want to do heavy calculations without freezing the app.
When you want to run simple tasks quickly on the main thread.
When you want to switch between different types of work easily.
Syntax
Kotlin
launch(Dispatchers.Main) { /* UI work here */ }
launch(Dispatchers.IO) { /* Disk or network work here */ }
launch(Dispatchers.Default) { /* CPU heavy work here */ }Dispatchers.Main runs on the main thread, good for UI updates.
Dispatchers.IO is for input/output tasks like files or network.
Examples
This runs a task on the main thread, good for UI updates.
Kotlin
CoroutineScope(Dispatchers.Main).launch {
println("Running on Main thread")
}This runs a task for input/output work like reading files.
Kotlin
CoroutineScope(Dispatchers.IO).launch {
println("Running on IO thread")
}This runs CPU-heavy tasks without blocking the main thread.
Kotlin
CoroutineScope(Dispatchers.Default).launch {
println("Running on Default thread")
}Sample Program
This program launches three coroutines on different dispatchers and prints the thread names to show where each runs.
Kotlin
import kotlinx.coroutines.* fun main() = runBlocking { launch(Dispatchers.Main) { println("Main: Thread = ${Thread.currentThread().name}") } launch(Dispatchers.IO) { println("IO: Thread = ${Thread.currentThread().name}") } launch(Dispatchers.Default) { println("Default: Thread = ${Thread.currentThread().name}") } }
OutputSuccess
Important Notes
Dispatchers.Main requires a platform that supports a main thread, like Android or JavaFX.
Dispatchers.IO uses a shared pool of threads optimized for blocking IO tasks.
Dispatchers.Default is optimized for CPU-intensive work and uses a shared pool of threads.
Summary
Dispatchers.Main is for UI work on the main thread.
Dispatchers.IO is for input/output tasks like files and network.
Dispatchers.Default is for CPU-heavy tasks to keep the app responsive.