Kotlin Coroutines are the standard way to write asynchronous code on Android without blocking the main thread. Networking, database access, and file I/O all take time — run them directly on the main thread and your app freezes, triggering an Application Not Responding (ANR) error. This Kotlin Coroutines tutorial covers the core building blocks you need to use them confidently in a real Android app.
What Is a Coroutine?
A coroutine is a lightweight, suspendable computation. Unlike a thread, a coroutine doesn’t map 1:1 to an OS thread — thousands of coroutines can run on just a few real threads, because a coroutine can “suspend” at a point where it’s waiting (like a network call) and free up the thread for other work, then resume later exactly where it left off.
Add the dependency to your module’s build.gradle.kts:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
launch vs async
Coroutines are started with a coroutine builder. The two you’ll use most are launch and async.
launch starts a coroutine that doesn’t return a result — it’s “fire and forget” work like updating the UI or writing a log.
lifecycleScope.launch {
val user = repository.fetchUser(userId)
nameTextView.text = user.name
}
async starts a coroutine that returns a result via a Deferred, which you unwrap with await(). Use it when you need the result back, especially when running two things in parallel.
lifecycleScope.launch {
val userDeferred = async { repository.fetchUser(userId) }
val postsDeferred = async { repository.fetchPosts(userId) }
val user = userDeferred.await()
val posts = postsDeferred.await()
render(user, posts)
}
Because both async calls start before either await() is called, the two network requests run concurrently instead of one after the other.
Dispatchers: Choosing Where Code Runs
A Dispatcher decides which thread (or thread pool) a coroutine runs on:
Dispatchers.Main— the Android UI thread. Use it for anything that touches views.Dispatchers.IO— a large pool optimized for blocking I/O: network calls, disk reads, database queries.Dispatchers.Default— a pool sized to your CPU cores, for CPU-heavy work like sorting large lists or parsing JSON.
Switch dispatchers with withContext, which suspends until the block finishes and then returns you to the original context:
suspend fun fetchUser(id: String): User = withContext(Dispatchers.IO) {
api.getUser(id) // runs on the IO dispatcher
} // execution resumes on the original dispatcher here
Structured Concurrency and CoroutineScope
Every coroutine runs inside a CoroutineScope. Structured concurrency means a scope’s lifetime controls its children’s lifetime: cancel the scope, and every coroutine launched inside it is cancelled too. This is what prevents the classic “fragment was destroyed but the network call kept running and crashed on the old view” bug.
On Android you rarely create a scope manually — Jetpack already ties one to each lifecycle-aware component:
lifecycleScope— tied to an Activity or Fragment’s lifecycle, cancelled when it’s destroyed.viewModelScope— tied to a ViewModel, cancelled when the ViewModel is cleared.
class UserViewModel(private val repository: UserRepository) : ViewModel() {
private val _user = MutableStateFlow<User?>(null)
val user: StateFlow<User?> = _user
fun loadUser(id: String) {
viewModelScope.launch {
_user.value = repository.fetchUser(id)
}
}
}
If the user navigates away before fetchUser finishes, viewModelScope is cancelled automatically — no manual cleanup, no leaked callback.
suspend Functions
The suspend keyword marks a function that can pause and resume without blocking the thread. A suspend function can only be called from another suspend function or from inside a coroutine builder like launch:
suspend fun fetchUser(id: String): User {
delay(1000) // suspends, doesn't block the thread
return api.getUser(id)
}
Most modern networking libraries (Retrofit, Ktor) and Room’s database queries already expose suspend versions, so you often don’t write the low-level dispatcher-switching yourself — you just call them from inside lifecycleScope.launch or viewModelScope.launch.
Handling Errors
Wrap coroutine code in a regular try/catch — exceptions propagate just like in synchronous code:
viewModelScope.launch {
try {
val user = repository.fetchUser(id)
_user.value = user
} catch (e: IOException) {
_error.value = "Network error, please try again."
}
}
Key Takeaways
- Use
launchfor fire-and-forget work,async/awaitwhen you need a result or want to run tasks in parallel. - Pick the right
Dispatcher:Mainfor UI,IOfor network/disk,Defaultfor CPU-heavy work. - Prefer
viewModelScopeandlifecycleScopeover manually created scopes — they cancel automatically and prevent leaks. - Mark long-running functions
suspendso they can be called safely from a coroutine without blocking any thread.
Once this clicks, pair it with our guide on mutableStateOf vs StateFlow in Jetpack Compose to see how coroutines and Compose state work together in a real screen.