Kotlin · Module 6 · Lesson 21 min read

Coroutines & Flow

Why coroutines?

On Android, the main thread draws the UI. Network or database work there freezes the app, and after ~5 seconds Android shows "App Not Responding". Coroutines run long work without blocking, in code that reads top to bottom.

suspend functions

kotlin
suspend fun fetchUser(id: Int): User {
    delay(1000)              // suspends, doesn't block the thread
    return api.getUser(id)
}

A suspend function can pause and resume. It can only be called from another suspend function or a coroutine.

Starting coroutines

BuilderReturnsUse
launch { }Jobfire and forget (save, log, update the UI)
async { }Deferred<T>a result: call .await()
runBlocking { }the resultonly in main() or tests

Structured concurrency

Coroutines run in a scope: on Android, viewModelScope or lifecycleScope. When the screen or ViewModel is destroyed, its coroutines are cancelled automatically, so there are no leaks.

Dispatchers: where the code runs

  • Dispatchers.Main: UI updates.
  • Dispatchers.IO: network, files, the database.
  • Dispatchers.Default: CPU-heavy work. Switch with withContext(Dispatchers.IO) { … }.

Running in parallel

kotlin
val a = async { fetchA() }
val b = async { fetchB() }
show(a.await(), b.await())     // both run at the same time

Flow: streams of values

Flow<T> emits many values over time: search results, database changes, a ticking timer. Use StateFlow to hold UI state in a ViewModel, and collect it in the UI.

💻 This lesson uses the kotlinx-coroutines library (included in Android projects). Try it in Android Studio or at play.kotlinlang.org.

Example

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

suspend fun fetchUser(id: Int): String {
    delay(300)                       // pretend network call
    return "User#$id"
}

suspend fun fetchPosts(id: Int): Int {
    delay(300)
    return id * 3
}

fun countdown(from: Int): Flow<Int> = flow {
    for (i in from downTo 1) {
        emit(i)
        delay(100)
    }
}

fun main() = runBlocking {
    val start = System.currentTimeMillis()
    val user = async { fetchUser(7) }        // both start now…
    val posts = async { fetchPosts(7) }
    println("${user.await()} has ${posts.await()} posts")       // …finish in ~300 ms
    println("Took ~${System.currentTimeMillis() - start} ms (not 600)")

    val job = launch {
        repeat(10) { i -> println("Working $i…"); delay(100) }
    }
    delay(350)
    job.cancel()                             // structured cancellation
    println("Cancelled the job")

    val heavy = withContext(Dispatchers.Default) { (1..1_000_000).sumOf { it.toLong() } }
    println("Sum on Default dispatcher: $heavy")

    countdown(3).map { "⏱ $it" }.collect { println(it) }
    println("Lift off! 🚀")
}