KtKotlin
AdvancedLesson 14 of 16

Coroutines & Flow – Kotlin

Concurrency with suspend, launch, async, dispatchers, cancellation, and Flow.

Coroutines are lightweight, suspendable computations. A suspend function can pause (e.g. delay, network access) without blocking a thread. You need the library kotlinx-coroutines-core. launch starts a coroutine without a result, and runBlocking bridges the normal world (e.g. main) with it.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000)          // pauses, but does not block a thread
        println("World")
    }
    println("Hello")         // appears first
}

async starts a coroutine with a result (Deferred), and await() retrieves it. This way independent tasks run in parallel instead of one after another. coroutineScope ensures structured concurrency: the block ends only when all children are done, and an error cancels the siblings.

suspend fun holePreis(): Int { delay(500); return 100 }
suspend fun holeRabatt(): Int { delay(500); return 20 }

suspend fun endpreis(): Int = coroutineScope {
    val preis = async { holePreis() }
    val rabatt = async { holeRabatt() }
    preis.await() - rabatt.await()       // takes about 0.5 s instead of 1 s
}

fun main() = runBlocking {
    println("Final price: ${endpreis()}")   // Final price: 80
}

Dispatchers determine which threads a coroutine runs on: Dispatchers.Default (CPU work), Dispatchers.IO (blocking I/O), Dispatchers.Main (UI, e.g. Android). With withContext you switch the context. Coroutines can be cancelled cooperatively – this is checked at every suspension point:

suspend fun ladeDaten(): String = withContext(Dispatchers.IO) {
    delay(200)               // simulates blocking I/O
    "Data"
}

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(10) { i ->
                println("Work $i")
                delay(300)
            }
        } finally {
            println("Cleaning up")
        }
    }
    delay(700)
    job.cancelAndJoin()      // Work 0, 1, 2 – then Cleaning up
    println(ladeDaten())     // Data
    println(withTimeoutOrNull(100) { delay(500); "too slow" })   // null
}

Flow is an asynchronous data stream (cold: it starts only when collected with collect). It suits sensor data, database updates, or websocket messages, and offers the same operators as collections.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun zaehle(): Flow<Int> = flow {
    for (i in 1..3) {
        delay(100)
        emit(i)
    }
}

fun main() = runBlocking {
    zaehle()
        .map { it * it }
        .filter { it > 1 }
        .collect { println(it) }     // 4, 9
}
WarningNever block inside a coroutine with Thread.sleep or the like – use delay. Do not use GlobalScope: coroutines without a parent scope are not cleaned up along with it. And do not silently swallow CancellationException, otherwise the coroutine can no longer be cancelled.
TiprunBlocking blocks the calling thread – fine for main and tests, but not in normal application code. On Android you use viewModelScope and lifecycleScope.