Skip to content
Kotlin

Coroutines

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

By EZ4Code Team
coroutineasyncconcurrency

Code

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")
}

Explanation

Coroutines are lightweight suspendable computations built on the kotlin.coroutines library. launch starts a fire-and-forget job while async returns a Deferred whose result you await. Structured concurrency scopes like runBlocking and supervisorScope enforce that children complete before the parent returns and propagate cancellation cleanly.

More Kotlin Snippets