0
0
Kotlinprogramming~5 mins

Coroutine context and dispatchers in Kotlin

Choose your learning style9 modes available
Introduction

Coroutine context and dispatchers help control where and how coroutines run. They decide the thread or thread pool used for running tasks.

When you want to run a task on the main UI thread to update the screen.
When you need to do heavy work like reading files or network calls without freezing the app.
When you want to switch between background and main threads smoothly.
When you want to organize coroutines with specific settings like names or error handlers.
Syntax
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.

Examples
This runs the coroutine on a shared background thread pool for CPU work.
Kotlin
launch(Dispatchers.Default) {
    println("Running on Default dispatcher")
}
This runs the coroutine on a thread pool optimized for blocking IO tasks.
Kotlin
launch(Dispatchers.IO) {
    println("Running on IO dispatcher")
}
This runs the coroutine on the main thread, useful for UI updates.
Kotlin
launch(Dispatchers.Main) {
    println("Running on Main dispatcher")
}
You can combine dispatchers with other context elements like names.
Kotlin
val context = Dispatchers.Default + CoroutineName("MyCoroutine")
launch(context) {
    println("Coroutine with a name")
}
Sample Program

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.

Kotlin
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}")
    // }
}
OutputSuccess
Important Notes

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.

Summary

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.