Coroutines & Flow – Kotlin
Nebenläufigkeit mit suspend, launch, async, Dispatchers, Cancellation und Flow.
Coroutines sind leichtgewichtige, unterbrechbare Berechnungen. Eine suspend-Funktion kann pausieren (z. B. delay, Netzwerkzugriff), ohne einen Thread zu blockieren. Du brauchst die Bibliothek kotlinx-coroutines-core. launch startet eine Coroutine ohne Ergebnis, runBlocking verbindet die normale Welt (z. B. main) mit ihr.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000) // pausiert, blockiert aber keinen Thread
println("Welt")
}
println("Hallo") // erscheint zuerst
}async startet eine Coroutine mit Ergebnis (Deferred), await() holt es ab. So laufen unabhängige Aufgaben parallel statt nacheinander. coroutineScope sorgt für Structured Concurrency: Der Block endet erst, wenn alle Kinder fertig sind, und ein Fehler bricht die Geschwister ab.
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() // Dauer ca. 0,5 s statt 1 s
}
fun main() = runBlocking {
println("Endpreis: ${endpreis()}") // Endpreis: 80
}Dispatchers legen fest, auf welchen Threads eine Coroutine läuft: Dispatchers.Default (CPU-Arbeit), Dispatchers.IO (blockierende I/O), Dispatchers.Main (UI, z. B. Android). Mit withContext wechselst du den Kontext. Coroutines lassen sich kooperativ abbrechen – an jedem Suspension-Point wird geprüft:
suspend fun ladeDaten(): String = withContext(Dispatchers.IO) {
delay(200) // simuliert blockierende I/O
"Daten"
}
fun main() = runBlocking {
val job = launch {
try {
repeat(10) { i ->
println("Arbeit $i")
delay(300)
}
} finally {
println("Aufräumen")
}
}
delay(700)
job.cancelAndJoin() // Arbeit 0, 1, 2 – dann Aufräumen
println(ladeDaten()) // Daten
println(withTimeoutOrNull(100) { delay(500); "zu langsam" }) // null
}Flow ist ein asynchroner Datenstrom (kalt: er startet erst beim Einsammeln mit collect). Er passt zu Sensordaten, Datenbank-Updates oder Websocket-Nachrichten und kennt dieselben Operatoren wie 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
}Thread.sleep oder ähnlichem – nutze delay. Nutze GlobalScope nicht: Coroutines ohne Elternscope werden nicht mit aufgeräumt. Und fange CancellationException nicht still ab, sonst lässt sich die Coroutine nicht mehr abbrechen.runBlocking blockiert den aufrufenden Thread – gut für main und Tests, aber nicht im normalen Anwendungscode. Auf Android nutzt du viewModelScope und lifecycleScope.