Skip to content
Kotlin

Coroutines

Use launch, async, await, and structured concurrency with supervisorScope.

#coroutine#async#concurrency

Code

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    // launch - fire and forget
    launch {
        delay(100)
        println("background")
    }

    // async - returns a Deferred
    val deferred = async {
        delay(50)
        42
    }
    println("result = ${deferred.await()}")

    // Parallel fetch
    suspend fun fetch(url: String): String {
        delay(50)
        return "data from $url"
    }

    val results = awaitAll(
        async { fetch("a") },
        async { fetch("b") },
        async { fetch("c") },
    )
    println(results)

    // Structured concurrency with supervisor
    supervisorScope {
        launch { delay(50); println("child 1 done") }
        launch { delay(30); println("child 2 done") }
    }

    // Cancellation
    val job = launch {
        repeat(10) { i ->
            try { delay(20) } catch (e: CancellationException) { throw e }
            println("tick $i")
        }
    }
    delay(50)
    job.cancelAndJoin()
    println("done")
}