Kotlin

coroutineScope and Structured Concurrency

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`coroutineScope { }` waits for ALL its children before returning. If any child throws, the others are cancelled. The cornerstone of structured concurrency — no leaked coroutines.
Kotlin
Raw
import kotlinx.coroutines.*

suspend fun fetchAll(ids: List<Int>): List<String> = coroutineScope {
    ids.map { id ->
        async {
            delay(100)
            "data-$id"
        }
    }.awaitAll()
    // coroutineScope returns ONLY when every child has completed.
    // If fetchAll throws, all children are cancelled.
}

suspend fun riskyParallel(): String = coroutineScope {
    val a = async { delay(200); "A" }
    val b = async { delay(50);  throw RuntimeException("boom") }
    a.await() + b.await()         // throws — `a` is cancelled automatically
}

fun main() = runBlocking {
    println(fetchAll(listOf(1, 2, 3)))

    try {
        riskyParallel()
    } catch (e: Exception) {
        println("caught: ${e.message}")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.