Coroutines are Kotlin’s structured concurrency: launch starts a job, async returns a Deferred value, and withContext switches threads. On Android, viewModelScope cancels work when the ViewModel clears. Use Dispatchers.Main for UI, IO for network and disk, and Flow when you have multiple values over time.
This Kotlin cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- suspend: A function that can call other suspend functions without blocking a thread.
- launch: Fire-and-forget Job on a scope. Exceptions cancel the parent unless you handle them.
- async:
await()the result. UsecoroutineScopeso failures cancel siblings. - Dispatchers:
Main,IO,Default. Do notDispatchers.IOthen update Views without switching back. - withContext: Switch dispatcher for a block and return a value.
- viewModelScope: AndroidX. Cancelled in
onCleared. - Flow: Cold stream.
collectin a coroutine.stateInfor UI state. - Cancel: Cooperative. Check
ensureActive()in loops.TimeoutCancellationExceptionis a cancellation.
Copy-paste examples
ViewModel load with IO and Main
Catch at the use-case boundary. async + await pairs well for two independent calls.
class ProjectVm(
private val api: ProjectApi
) : ViewModel() {
var title: String = ""
private set
fun load(id: Int) {
viewModelScope.launch {
try {
title = withContext(Dispatchers.IO) { api.fetch(id).title }
} catch (e: Exception) {
title = "Unavailable"
}
}
}
}Parallel async inside a scope
coroutineScope waits for children. If one fails, the other is cancelled.
suspend fun dashboard(api: ProjectApi, id: Int): Pair<Project, Stats> =
coroutineScope {
val p = async { api.fetch(id) }
val s = async { api.stats(id) }
p.await() to s.await()
}Common mistakes
- Using
GlobalScope.launchin an Activity — work outlives the screen. - Calling
runBlockingon the main thread in production Android code. - Updating RecyclerView from
Dispatchers.IO. - Swallowing
CancellationExceptionin a broadcatch (e: Exception)so cancel looks like a bug.
FAQ
- Coroutines vs threads? Coroutines are lighter and structured. They still use thread pools (IO/Default). You write sequential suspend code instead of callbacks.
- CallbackFlow vs Flow builders?
flow { }for compute.callbackFlowwhen wrapping listeners (location, sensors). Always close or awaitClose.
- Do I need RxJava still? Not for new Kotlin Android apps unless a library forces it. Coroutines + Flow cover the usual cases.
Related Kotlin cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds mobile app development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.