Coroutine Context in Kotlin

From the Kotlin cheat sheet · Coroutines · verified Jul 2026

Coroutine Context

Dispatchers and coroutine context

kotlin
// Dispatchers
fun main() = runBlocking {
    launch(Dispatchers.Main) {
        // UI updates (Android)
    }

    launch(Dispatchers.IO) {
        // IO operations
        val data = readFile()
    }

    launch(Dispatchers.Default) {
        // CPU-intensive work
        val result = complexCalculation()
    }

    launch(Dispatchers.Unconfined) {
        // Not confined to any thread
    }
}

// withContext - switching context
suspend fun fetchData(): String = withContext(Dispatchers.IO) {
    // Perform IO operation
    readFromNetwork()
}

suspend fun processData() = withContext(Dispatchers.Default) {
    // CPU-intensive processing
    parseData()
}

// Flow - cold asynchronous stream
fun numbersFlow(): Flow<Int> = flow {
    for (i in 1..5) {
        delay(100)
        emit(i)
    }
}

fun main() = runBlocking {
    numbersFlow()
        .map { it * it }
        .filter { it % 2 == 0 }
        .collect { println(it) }
}
💡 Dispatchers determine which thread coroutines run on
⚡ Flow is cold (starts on collect), Channel is hot
📌 withContext switches context without creating new coroutine
🟢 StateFlow holds state, SharedFlow broadcasts events

More Kotlin tasks

Back to the full Kotlin cheat sheet