Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 104 ยท Coroutines and Background Work

Coroutines on Android

Use Kotlin coroutines on Android: Main, IO and Default dispatchers, viewModelScope and lifecycleScope, main-safe functions, cancellation on leaving a screen and error handling.

Android has one thread that matters more than the others: the main thread (also called the UI thread). It draws every frame, delivers every tap and calls your lifecycle callbacks. If it is busy for more than a few milliseconds, frames are dropped and the app feels slow; if it is blocked for several seconds, the system shows the "App isn't responding" dialog. Anything slow, such as a network call, a database query or parsing a big file, must run somewhere else, and the result must come back to the main thread so you can update the screen.

Kotlin coroutines are the standard way to do that on Android. You already know the language side from Coroutines: Getting Started and Structured Concurrency. This lesson is about the Android side: which dispatcher to use, which scope to launch in, how work stops when the user leaves a screen, and what happens when something throws. The real Android classes cannot run on this site, so those snippets are read-only. The TryIts build a small stand-in with a single "UI thread" and real coroutines, so the behavior you see is genuine, only the Android names are simulated.

Dispatchers: where code runs

A coroutine runs on a dispatcher, which picks the thread. Android uses three:

Dispatcher Threads Use it for
Dispatchers.Main The one main thread Updating UI state, calling other suspend functions, light work
Dispatchers.IO A large shared pool (up to 64 threads) Blocking calls: files, databases, network, anything that waits
Dispatchers.Default One thread per CPU core CPU-heavy work: sorting big lists, parsing, image processing

There is also Dispatchers.Main.immediate, which runs the code right away if you are already on the main thread instead of posting it to the queue first. viewModelScope and lifecycleScope use it by default.

Dispatchers.Main needs the kotlinx-coroutines-android library, which is added automatically by the AndroidX ViewModel and Lifecycle libraries. On a plain JVM, as in unit tests, Dispatchers.Main does not exist until you install a test dispatcher (see Unit Testing ViewModels and Flows).

Switch with withContext. It runs a block on another dispatcher, suspends the caller while it runs, and returns the result:

Kotlin
// read-only example
suspend fun loadSettingsText(file: File): String =
    withContext(Dispatchers.IO) {
        file.readText()          // blocking call, safe here
    }

Main-safety

A function is main-safe when it is safe to call from the main thread because it moves its own blocking work off it. This is the most important convention in Android coroutine code:

Every suspend function you write should be main-safe. The caller should never need to know which thread the work happens on.

Retrofit's suspend functions and Room's suspend DAO methods are main-safe: they switch threads internally. Your repository should be too, by wrapping its own blocking work in withContext(ioDispatcher). Then a ViewModel can simply call it from viewModelScope, which starts on Main:

Kotlin
// read-only example
class ProfileViewModel(private val repo: ProfileRepository) : ViewModel() {

    private val _state = MutableStateFlow(ProfileState())
    val state: StateFlow<ProfileState> = _state

    fun load() {
        viewModelScope.launch {                       // starts on Main
            _state.update { it.copy(loading = true) }
            val profile = repo.loadProfile()          // main-safe: repo switches threads
            _state.update { it.copy(loading = false, profile = profile) }
        }
    }
}

Note what is missing: no withContext in the ViewModel, no callback, no manual "back to the main thread". After loadProfile() returns, the code continues on Main automatically.

Two more habits help. Inject dispatchers instead of writing Dispatchers.IO in the middle of a class (class Repo(private val io: CoroutineDispatcher = Dispatchers.IO)), so tests can replace them. And never call runBlocking in production Android code: it blocks the very thread you were trying to keep free.

The first TryIt shows why this matters. It creates a single-threaded "UI thread" and runs a ticker on it that stands in for frame rendering. Then it runs the same slow job twice: once directly on the UI thread and once with withContext. The ticker records the longest gap between two ticks.

Kotlin Blocking the main thread versus main-safety (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the real world the "ticker" is the Choreographer, which wants a frame every 16 ms on a 60 Hz screen. The idea is the same: one blocked thread freezes everything that shares it.

Scopes: who owns the work

Every coroutine needs a scope, and the scope decides when the coroutine is cancelled. Android provides ready-made scopes tied to a lifecycle:

flowchart TD
    A["Activity or Fragment"] -->|"lifecycleScope"| B["Cancelled in onDestroy"]
    V["ViewModel"] -->|"viewModelScope"| C["Cancelled in onCleared"]
    P["Composable"] -->|"rememberCoroutineScope"| D["Cancelled when it leaves the composition"]
    G["GlobalScope"] -->|"never cancelled"| E["Leaks until the process dies"]

Each scope ends when its owner ends. GlobalScope has no owner, so avoid it.

  • viewModelScope: lives as long as the ViewModel, so it survives rotation and is cancelled when the user leaves the screen for good. Use it for loading data and saving what the user did.
  • lifecycleScope: tied to the activity or fragment, so it is cancelled on rotation. Use it for work that only matters while that UI exists. Do not collect flows in it carelessly, see Collecting Flows Safely.
  • rememberCoroutineScope(): in Compose, for launching work from event handlers such as a button click. See Side Effects.
  • A custom scope (CoroutineScope(SupervisorJob() + Dispatchers.Default)) for work that must outlive any screen, such as an app-wide cache. Create it once, in the application class or through injection. For work that must be guaranteed to finish, use WorkManager instead.

GlobalScope is almost always a bug: nothing cancels it, so a request started from a closed screen continues, holds references to dead objects and may update state nobody is watching.

Cancellation when the user leaves

Structured concurrency is what makes the scopes useful. When a scope is cancelled, all its children are cancelled at their next suspension point. A network call that is suspended in the middle of the request is abandoned; the finally blocks run; no code after the suspension executes.

Cancellation is cooperative. Library functions such as delay, withContext, Retrofit and Room check for it. Your own loops must too, with isActive, ensureActive() or by calling a suspending function. A tight CPU loop that never suspends is never cancelled:

Kotlin
// read-only example
suspend fun checksum(chunks: List<ByteArray>): Long = withContext(Dispatchers.Default) {
    var sum = 0L
    for (chunk in chunks) {
        ensureActive()                 // stop quickly if the scope was cancelled
        sum += chunk.sum()
    }
    sum
}

Exceptions

How a failure travels depends on how you started the coroutine:

  • launch: an uncaught exception goes up to the parent. With a plain Job it cancels the siblings and the parent; viewModelScope and lifecycleScope use a SupervisorJob, so one failing child does not cancel the others. With no handler, an uncaught exception crashes the app.
  • async: the exception is stored and thrown when you call await(). Catch it there.
  • try/catch around a suspend call works as you expect. Catch the specific exceptions you can handle, for example IOException, and show an error state.
  • CancellationException is special: it is how cancellation is delivered and must never be swallowed. If you catch Exception in a suspend function, rethrow CancellationException, or the coroutine will not stop. This is also why runCatching { suspendCall() } can hide cancellation: prefer a targeted try/catch.
  • CoroutineExceptionHandler is a last resort for launch at the top of a scope: it can log or report, but the coroutine is already dead.

See Exceptions in Coroutines for the full rules.

The second TryIt rebuilds the idea of viewModelScope from the pieces: a SupervisorJob, the simulated Main dispatcher and an exception handler. It runs three loads, one of them failing. Then it repeats the experiment on a second ViewModel whose user leaves after 100 ms.

Kotlin A viewModelScope stand-in: failures and cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In scenario A the failing feed reaches the handler, yet the profile and badge still finish, because the SupervisorJob keeps siblings independent. In scenario B the profile load is cancelled while it is suspended inside withContext, its finally block runs with cancelled=true, and the badge job never prints anything.

Putting it together

A typical Android function chain, from tap to screen:

  1. A composable calls viewModel.refresh(), running on the main thread.
  2. The ViewModel launches in viewModelScope (Main) and sets a loading state.
  3. It calls a repository suspend function. The repository switches to IO for the blocking part, if it has any.
  4. The result returns to Main, and the ViewModel updates a StateFlow.
  5. If the user leaves, onCleared() cancels the scope, and step 3 is abandoned.

You never wrote a thread, a callback or a Handler, and still the work stopped by itself when nobody needed it.

Common mistakes

  • Calling blocking code on Main because "it is only a small read". Small reads add up; move all disk and network work off Main.
  • Using GlobalScope or an unowned CoroutineScope(...) inside an Activity or ViewModel.
  • Hard-coding Dispatchers.IO deep inside classes, which makes tests slow and flaky. Inject the dispatcher.
  • Catching Exception and swallowing CancellationException, leaving cancelled coroutines running.
  • Launching work in the Activity that belongs in the ViewModel, so rotation restarts the request.
  • Switching dispatchers in the caller instead of the callee. Make the suspend function main-safe once, and every caller benefits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which dispatcher is the best fit for a CPU-heavy task such as sorting a large list?

    Default has about one thread per CPU core, which suits computation. IO has a large pool meant for blocking waits, and Main must stay free for the UI.
  2. 2. What does it mean for a suspend function to be main-safe?

    Main-safe functions hide their threading. Callers do not need withContext, and the function does not freeze the UI no matter where it is called from.
  3. 3. The user leaves a screen while its ViewModel is loading data. What happens to the work in viewModelScope?

    onCleared cancels viewModelScope, and every child coroutine is cancelled at its next suspension point, with finally blocks still running.
  4. 4. Why is it risky to write catch (e: Exception) around a suspend call without rethrowing CancellationException?

    Cancellation is delivered as a CancellationException. Swallowing it hides the cancellation from the coroutine machinery, so the work does not stop as expected.
  5. 5. A launch inside viewModelScope throws. What happens to its siblings?

    A SupervisorJob stops a child's failure from cancelling its siblings. The uncaught exception still goes to the handler or crashes the app if there is none.

Summary

  • The main thread draws the UI; never block it. Use Dispatchers.IO for blocking waits, Default for CPU work and Main for UI updates.
  • Make every suspend function main-safe with withContext, and inject dispatchers so tests can replace them.
  • viewModelScope survives rotation and ends in onCleared; lifecycleScope ends with the activity or fragment; rememberCoroutineScope ends with the composable. Avoid GlobalScope.
  • Cancelling a scope cancels all children at their next suspension point; long loops must cooperate with ensureActive().
  • launch reports uncaught exceptions to the parent, async rethrows at await(), and CancellationException must never be swallowed.
  • Real Android scopes are read-only here; the TryIts use a one-thread stand-in with real coroutines.

Next: Collecting Flows Safely