Coroutine context and dispatchers help control where and how coroutines run. They decide the thread or thread pool used for running tasks.
Coroutine context and dispatchers in Kotlin
launch(Dispatchers.IO) {
// code to run in IO dispatcher
}
launch(Dispatchers.Main) {
// code to run on main thread
}
val context = Dispatchers.Default + CoroutineName("MyCoroutine")Dispatchers.IO is for input/output tasks like files or network.
Dispatchers.Main runs on the main thread, good for UI updates.
launch(Dispatchers.Default) {
println("Running on Default dispatcher")
}launch(Dispatchers.IO) {
println("Running on IO dispatcher")
}launch(Dispatchers.Main) {
println("Running on Main dispatcher")
}val context = Dispatchers.Default + CoroutineName("MyCoroutine") launch(context) { println("Coroutine with a name") }
This program launches two coroutines each on a different dispatcher. It prints the thread name to show where each runs. The Dispatchers.Main coroutine is commented out because it requires platform support.
import kotlinx.coroutines.* fun main() = runBlocking { launch(Dispatchers.Default) { println("Default dispatcher: Running on thread ${Thread.currentThread().name}") } launch(Dispatchers.IO) { println("IO dispatcher: Running on thread ${Thread.currentThread().name}") } // Dispatchers.Main requires platform support (e.g., Android). It may cause errors on JVM console apps. // launch(Dispatchers.Main.immediate) { // println("Main dispatcher: Running on thread ${Thread.currentThread().name}") // } }
Dispatchers.Main requires platform support (like Android). On JVM console apps, it may cause errors.
You can combine multiple context elements using the + operator.
Use runBlocking in main functions to wait for coroutines to finish.
Coroutine context controls where coroutines run.
Dispatchers specify the thread or thread pool for coroutines.
Use Dispatchers.Main for UI, Dispatchers.IO for IO tasks, and Dispatchers.Default for CPU work.