Kotlin 2 cheatsheet
Kotlin 2: Coroutines
6 common Kotlin 2 tasks.
Add coroutines
Coroutine support is a separate library. Add it to your Gradle dependencies.
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
Start coroutines
runBlocking bridges regular code to coroutines. launch starts concurrent work and returns a Job.
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(100)
println("world")
}
println("hello")
}
Run work in parallel
async starts work that returns a value, and await gets it. Both calls below run at the same time.
suspend fun total(): Int = coroutineScope {
val a = async { fetchA() }
val b = async { fetchB() }
a.await() + b.await()
}
Switch dispatcher
Run blocking or CPU-heavy work on a suitable dispatcher without blocking the caller.
val text = withContext(Dispatchers.IO) { File("data.txt").readText() }
Stream values with Flow
A flow emits values over time and is collected from a coroutine.
fun ticks(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
ticks().collect { println(it) }
Limit how long work can take
Cancel a block that takes too long.
val result = withTimeoutOrNull(1_000) { slowCall() }