Kotlin coroutines are a lightweight alternative to Java threads. They make writing asynchronous code easy ...when you know how to use them. Coroutine scope, context, dispatchers⦠These terms seem confusing and even intimidating. This cheatsheet aims to fix this confusion and provides a three-step routine to launch coroutines accompanied with code examples.
Cheatsheet
Code Examples
runBlocking {
// launch a new job launch() - it does NOT return a result
val job = launch {
println("Binary representation of 2 is ${Integer.toBinaryString(2)}")
}
// let's wait until the first job is done
job.join()
// async: returns a result
val tenInBinary = async {
Integer.toBinaryString(10)
}
println("Binary representation of 10 is ${tenInBinary.await()}")
// let's launch several tasks at once!
coroutineScope {// create a new coroutine scope for structured concurrency
val numbersForBinaryConversion = listOf(42, 170, 682) // arbitrary numbers
numbersForBinaryConversion.map {
launch { // launches a job without a result
println("Binary representation of $it is ${Integer.toBinaryString(it)}")
}
}.joinAll() // waits for ALL jobs in tghe list
}
}
Top comments (1)
Thanks for this! I'm still trying to figure coroutines out and this definitely helps a lot.