Blog – Page 6

Kotlin Coroutines on Android: A Practical Guide

Kotlin coroutines let you write asynchronous code that reads like ordinary sequential code. On Android they solve two problems: keeping long-running work off the main thread so the UI doesn’t freeze, and cancelling that work automatically when the screen that started it goes away. This guide covers what you need day to day: suspend functions, scopes, dispatchers, structured concurrency, cancellation, exceptions and testing.

I first wrote about coroutines in 2019 and 2020, when GlobalScope examples were everywhere. Those examples aged badly, so I merged both posts into this one and rewrote it around the patterns Android uses now.

Suspend functions

A suspend function can pause without blocking the thread it runs on. While it waits (for a network response, a database query, a delay), the thread is free to do other work. When the result is ready, the function resumes where it left off.

suspend fun loadProfile(id: String): Profile {
    val user = api.fetchUser(id)          // suspends, doesn't block
    val posts = api.fetchPosts(user.id)   // runs after the first call returns
    return Profile(user, posts)
}

Compare that with callbacks: no nesting, and you can use try/catch, loops and return the way you normally would. If you know async/await from JavaScript or C#, a call to a suspend function is like an implicit await.

You can only call a suspend function from another suspend function or from a coroutine. That restriction is the point: it forces every piece of async work to belong to some coroutine, which belongs to some scope.

Scopes: who owns the work

A coroutine scope defines how long its coroutines may live. Cancel the scope and everything started in it is cancelled. On Android you rarely create scopes yourself, because the lifecycle libraries give you the right ones:

  • viewModelScope: cancelled when the ViewModel is cleared. Use it for work that should survive rotation but not leaving the screen.
  • lifecycleScope: cancelled when the Activity or Fragment is destroyed.
  • rememberCoroutineScope() and LaunchedEffect in Compose: tied to the composable’s place in the UI.
class ProfileViewModel(private val repository: ProfileRepository) : ViewModel() {
    private val _state = MutableStateFlow<ProfileState>(ProfileState.Loading)
    val state: StateFlow<ProfileState> = _state

    fun load(id: String) {
        viewModelScope.launch {
            _state.value = try {
                ProfileState.Loaded(repository.loadProfile(id))
            } catch (e: IOException) {
                ProfileState.Error(e.message)
            }
        }
    }
}

Avoid GlobalScope. Its coroutines aren’t tied to anything, so they keep running after the user leaves the screen, can leak memory, and are hard to test. Most old tutorials (including my 2019 post) used it because it was the shortest thing that compiled.

Dispatchers: which thread runs the work

A dispatcher decides which thread or thread pool a coroutine runs on:

Dispatcher Use it for
Dispatchers.Main UI work and anything that touches views or Compose state
Dispatchers.IO Blocking I/O: files, raw sockets, legacy blocking APIs
Dispatchers.Default CPU-heavy work: parsing large JSON, sorting, image processing

viewModelScope and lifecycleScope start on Dispatchers.Main. To move a block elsewhere, use withContext:

suspend fun parseReport(raw: String): Report =
    withContext(Dispatchers.Default) {
        heavyParse(raw)
    }

The rule worth following is main-safety: a suspend function should be safe to call from the main thread, and it should switch dispatchers itself if it needs to. Room, Retrofit and Ktor already do this, so you don’t wrap their suspend calls in withContext(Dispatchers.IO).

Structured concurrency

Coroutines started inside another coroutine become its children. The parent doesn’t finish until all its children finish, and cancelling the parent cancels the children. This is what “structured concurrency” means, and it’s why coroutines don’t leak the way threads or callbacks do.

coroutineScope creates a child scope inside a suspend function. Combined with async, it’s the standard way to run things in parallel:

suspend fun loadDashboard(): Dashboard = coroutineScope {
    val profile = async { api.fetchProfile() }
    val feed = async { api.fetchFeed() }
    Dashboard(profile.await(), feed.await())
}

Both requests run at the same time. If one fails, the other is cancelled and the exception propagates to the caller, so you never end up with half a dashboard and a request still running in the background.

runBlocking looks similar but blocks the current thread until its body finishes. It exists to bridge blocking code (like a main function or an old test) into coroutines. Don’t use it in app code.

Cancellation is cooperative

Cancelling a coroutine doesn’t kill it. It sets a flag, and the coroutine stops the next time it reaches a suspension point. All suspend functions from kotlinx.coroutines (delay, withContext, Flow.collect and others) check for cancellation, so most code cancels correctly without any effort.

A tight loop of plain computation never suspends, though, so it won’t notice. Check explicitly:

suspend fun hashAll(files: List<File>): List<String> = withContext(Dispatchers.Default) {
    files.map { file ->
        ensureActive() // throws CancellationException if the scope was cancelled
        sha256(file)
    }
}

One trap: cancellation is delivered as a CancellationException. If you catch Exception broadly and swallow it, the coroutine keeps running after it should have stopped. Catch specific exceptions, or rethrow CancellationException.

Exceptions

How an exception travels depends on the builder:

  • launch treats an uncaught exception as a failure of the coroutine. It propagates to the parent, cancels the parent and its other children, and, if nothing handles it, crashes the app on Android. A try/catch around launch doesn’t help, because launch returns immediately. Catch inside the coroutine instead, as in the ViewModel above.
  • async holds the exception until you call await(), where it’s rethrown. (Inside coroutineScope, it still cancels the siblings right away.)

When one failing child shouldn’t cancel the others, use supervisorScope (or a SupervisorJob). viewModelScope already uses a SupervisorJob, so one failed launch doesn’t cancel the rest of the ViewModel’s work.

suspend fun syncAll(accounts: List<Account>) = supervisorScope {
    accounts.forEach { account ->
        launch {
            try {
                sync(account)
            } catch (e: IOException) {
                log("Sync failed for ${account.id}: ${e.message}")
            }
        }
    }
}

A CoroutineExceptionHandler is a last-resort hook for logging uncaught exceptions in a root scope. It doesn’t let you recover, so prefer handling errors where they happen.

Streams of values: Flow

A suspend function returns one value. For a stream of values over time (database changes, location updates, UI state), use Flow. In practice, a ViewModel exposes a StateFlow and the UI collects it:

@Composable
fun ProfileScreen(viewModel: ProfileViewModel) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    ProfileContent(state)
}

collectAsStateWithLifecycle() stops collecting when the app goes to the background, so you don’t keep doing work for a screen nobody sees. In the View system, repeatOnLifecycle(Lifecycle.State.STARTED) inside lifecycleScope does the same job.

Channels also exist for passing values between coroutines, but in app code you’ll reach for Flow far more often.

Testing

kotlinx-coroutines-test gives you runTest, which runs a test in a coroutine and skips delay calls using virtual time, so a test with a five-second timeout finishes instantly:

@Test
fun retriesThenSucceeds() = runTest {
    val api = FakeApi(failuresBeforeSuccess = 2)
    val result = fetchWithRetry(api, retryDelayMillis = 5_000)
    assertEquals("ok", result)
    assertEquals(3, api.calls)
}

To make code testable, inject dispatchers instead of hard-coding Dispatchers.IO deep inside a class. In ViewModel tests, replace Dispatchers.Main with Dispatchers.setMain(StandardTestDispatcher()) in a test rule, since there’s no Android main thread on the JVM.

Quick reference

  • Mark async work as suspend and make it main-safe.
  • Launch from viewModelScope, lifecycleScope or Compose effects. Never GlobalScope.
  • Use withContext to change dispatcher, and coroutineScope + async for parallel work.
  • Don’t swallow CancellationException.
  • Catch exceptions inside launch, and use supervisorScope when children should fail independently.
  • Expose state as StateFlow and collect it with lifecycle awareness.
  • Test with runTest and injected dispatchers.

The Kotlin coroutines guide covers the library in depth, and Android’s coroutines best practices page is a good checklist for app code. For background work that must run even after the app closes, coroutines aren’t enough on their own; that’s what WorkManager is for.


Android WorkManager: A Practical Guide to Background Work

WorkManager is the Jetpack library for background work that must finish even if the user leaves the app or the device restarts: uploading a photo, syncing data, sending logs. You describe the work and the conditions it needs (network, charging, enough storage), and WorkManager decides when to run it, retries it if it fails, and survives process death and reboots. This guide covers the APIs you’ll use in a modern Kotlin app.

I first wrote about WorkManager in 2019, when version 2.0 was new and examples were in Groovy with JCenter. I’ve rewritten the post for current WorkManager with coroutines.

When to use WorkManager

Android has several ways to do work off the main thread, and picking the wrong one causes most background bugs:

Situation Use
Work tied to a screen (load data while it’s visible) Coroutines in viewModelScope
Work that must complete even if the app closes, and can wait for the right conditions WorkManager
Work the user started and is watching right now (a long download, a workout) A foreground service, or WorkManager long-running work
Something at an exact time (an alarm clock, a calendar reminder) AlarmManager exact alarms

WorkManager is about guaranteed, deferrable work. It’s not for things that must happen at a precise second, and it’s not a replacement for coroutines inside a screen.

Setup

Add the KTX artifact, which includes coroutine support:

// build.gradle.kts (app module)
dependencies {
    implementation("androidx.work:work-runtime-ktx:<latest-version>")
    androidTestImplementation("androidx.work:work-testing:<latest-version>")
}

Check the release notes for the current version. WorkManager initializes itself on app start, so for most apps there’s nothing else to configure.

Writing a worker

Extend CoroutineWorker and put the work in doWork(), which is a suspend function. It runs on Dispatchers.Default by default, and you can call other suspend functions directly:

class UploadPhotoWorker(
    context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        val uri = inputData.getString(KEY_URI) ?: return Result.failure()
        return try {
            val url = PhotoApi.upload(Uri.parse(uri))
            Result.success(workDataOf(KEY_URL to url))
        } catch (e: IOException) {
            if (runAttemptCount < 3) Result.retry() else Result.failure()
        }
    }

    companion object {
        const val KEY_URI = "uri"
        const val KEY_URL = "url"
    }
}

The return value tells WorkManager what happened:

  • Result.success() means done, optionally with output data.
  • Result.retry() means try again later, using the backoff policy.
  • Result.failure() means give up. Work chained after this one is cancelled too.

inputData and output data are small key-value maps, limited to 10 KB. Pass IDs or URIs, not the content itself.

Scheduling work

One-time work with constraints

val request = OneTimeWorkRequestBuilder<UploadPhotoWorker>()
    .setInputData(workDataOf(UploadPhotoWorker.KEY_URI to photoUri.toString()))
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(NetworkType.UNMETERED)
            .setRequiresBatteryNotLow(true)
            .build()
    )
    .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
    .addTag("photo-upload")
    .build()

WorkManager.getInstance(context).enqueue(request)

The upload waits until the device is on Wi-Fi with a healthy battery, then runs. If it returns retry(), WorkManager waits 30 seconds, then 60, then 120, and so on.

Unique work

If a user taps “sync” five times, you don’t want five syncs. Unique work gives a job a name and lets you decide what happens on conflict:

WorkManager.getInstance(context).enqueueUniqueWork(
    "sync",
    ExistingWorkPolicy.KEEP, // ignore the new request if one is pending or running
    OneTimeWorkRequestBuilder<SyncWorker>().build()
)

REPLACE cancels the existing work and starts the new one, and APPEND_OR_REPLACE queues the new work after the existing one.

Periodic work

val dailySync = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.DAYS)
    .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
    .build()

WorkManager.getInstance(context).enqueueUniquePeriodicWork(
    "daily-sync",
    ExistingPeriodicWorkPolicy.KEEP,
    dailySync
)

The minimum interval is 15 minutes, and the exact run time is flexible: Android batches work to save battery. Always enqueue periodic work as unique work. Otherwise every app start adds another copy.

Chaining

Run work in sequence, passing each worker’s output to the next as input:

WorkManager.getInstance(context)
    .beginWith(listOf(compressPhoto1, compressPhoto2)) // these two run in parallel
    .then(uploadAll)
    .then(cleanUp)
    .enqueue()

If any step fails, the steps after it are cancelled.

Expedited and long-running work

For short, important work the user is waiting on, like sending a message, mark the request as expedited:

val send = OneTimeWorkRequestBuilder<SendMessageWorker>()
    .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
    .build()

Expedited work starts as soon as possible, but it’s subject to a system quota. The out-of-quota policy says what to do when the quota runs out. On Android 11 and lower, expedited work runs as a foreground service, so your worker should override getForegroundInfo() to provide the notification.

For work that runs for minutes, like a large download, call setForeground() from inside doWork() so the system keeps it alive and the user sees a notification. On Android 14 and up, the foreground service type must also be declared in the manifest.

Observing progress and results

Every request has an ID, and WorkManager exposes its state as a Flow:

WorkManager.getInstance(context)
    .getWorkInfoByIdFlow(request.id)
    .collect { info ->
        when (info?.state) {
            WorkInfo.State.RUNNING -> showProgress(info.progress.getInt("percent", 0))
            WorkInfo.State.SUCCEEDED -> showDone(info.outputData.getString(UploadPhotoWorker.KEY_URL))
            WorkInfo.State.FAILED -> showError()
            else -> Unit
        }
    }

Inside the worker, report progress with setProgress(workDataOf("percent" to 40)). You can also observe all work with a tag (getWorkInfosByTagFlow) or a unique name (getWorkInfosForUniqueWorkFlow). To stop work, call cancelWorkById, cancelAllWorkByTag or cancelUniqueWork.

Testing workers

The work-testing artifact lets you run a worker directly in a test, without scheduling it:

@Test
fun upload_withoutUri_fails() = runTest {
    val worker = TestListenableWorkerBuilder<UploadPhotoWorker>(
        context = ApplicationProvider.getApplicationContext()
    ).build()

    assertEquals(ListenableWorker.Result.failure(), worker.doWork())
}

For end-to-end checks of constraints and delays, WorkManagerTestInitHelper gives you a test driver that can mark constraints as met and skip initial delays.

Common mistakes

  • Using WorkManager for exact timing. It may run your work minutes or hours later. Use AlarmManager for exact times.
  • Enqueueing periodic work on every app start without enqueueUniquePeriodicWork.
  • Passing large data in inputData. Store it in a file or database and pass the ID.
  • Ignoring isStopped. The system can stop a worker when constraints are no longer met. CoroutineWorker cancels the coroutine, so make long loops check for cancellation (see my coroutines guide on cooperative cancellation).
  • Holding references to Activities or Views in a worker. Workers outlive your UI.

Android’s WorkManager guide covers advanced topics like custom initialization, multi-process apps and RxJava workers.