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}")
}
}
Create a free account and build your private vault. Share publicly whenever you want.