Coroutines
Use launch, async, await, and structured concurrency with supervisorScope.
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
Null Safety
Use nullable types, safe calls, Elvis, and smart casts for null-safe code.
Data Classes
Model immutable data with auto-generated equals, copy, and destructuring.
Extension Functions
Add methods to existing types with extensions and infix operators.
Sealed Classes
Model closed hierarchies and UI state with sealed classes and when.
When Expression
Branch on values, ranges, and types with when as statement or expression.
Collections
Filter, map, group, partition, and chunk with functional operators.