Coroutines basics: suspend and builders

Learn Kotlin Coroutines basics for Android, covering the suspend keyword, coroutine builders, and how to choose the right scope for your tasks. About 25 minutes.

Why it matters

  • Every async call in a modern Android app goes through a suspend function or a builder; picking the wrong one causes leaked coroutines, unhandled exceptions, or UI freezes.
  • Interviewers at mid and senior levels ask you to explain the Continuation mechanism and the difference between launch and async without hand-waving.
  • Builders define the Job hierarchy. Getting the hierarchy wrong means a cancelled screen keeps running network calls in the background.
  • withContext is the standard way to switch dispatchers inside a suspend chain. Using GlobalScope or a raw Thread instead breaks structured concurrency.

The simple explanation

  • A suspend function is like a chef who can pause mid-recipe, hand the plate to a waiter, and resume later without blocking the kitchen.
  • launch is 'start a side task and forget the result' (fire-and-forget).
  • async is 'start a side task and I will collect the result later' (a promise).
  • coroutineScope is a kitchen shift: when the shift ends, every station must be closed before the chef leaves.
  • supervisorScope is a kitchen where one station burning down does not shut the others.
  • withContext is 'move this step to a different station (thread pool) and bring the result back.'

The suspend keyword is a compile-time contract. The Kotlin compiler adds a hidden Continuation parameter to every suspend fun and turns its body into a state machine. When the function actually suspends, it saves its local state and returns a special COROUTINE_SUSPENDED marker to its caller; later the Continuation is resumed and the function carries on from where it stopped. While it is suspended, no thread is blocked. suspend alone does not move work to a background thread: blocking code inside a suspend function still blocks whatever thread runs it.

launch and async are coroutine builders: they start a new coroutine in a CoroutineScope. coroutineScope, supervisorScope and withContext are suspend functions that run a block in a new scope and return its result.

FunctionReturnsCaller waits?When a child fails
launchJobNo, returns at onceThe failure cancels the parent and its other children (unless the parent uses a SupervisorJob)
asyncDeferred<T>No, returns at onceSame as launch; await() also throws the exception
coroutineScopeT (block result)Yes, until the block and all its children finishCancels the other children and rethrows to the caller
supervisorScopeTYes, until the block and all its children finishOther children keep running; the failed child must handle its own error
withContextTYes, until the block and all its children finishCancels the other children and rethrows to the caller

withContext is the one you use most: it runs its block with a changed CoroutineContext (usually a different dispatcher), suspends the caller until the block is done, and returns the result.

In Android, viewModelScope (on a ViewModel) and lifecycleScope (on a LifecycleOwner) give you a ready-made scope that is cancelled when the ViewModel is cleared or the lifecycle is destroyed. Launch from those scopes, not from GlobalScope.

Suspend does not block the thread
Suspend does not block the thread The main thread launches a coroutine with viewModelScope.launch. The coroutine calls a suspend function that makes a network request, and suspends: its state is saved in a Continuation. The main thread stays free for frames and taps. When the result arrives, the Continuation resumes the coroutine on the main thread and it updates the UI state. Suspended: state saved in a Continuation Free to draw frames and handle taps Resumed where it stopped viewModelScope.launch suspend fun load() RESULT ARRIVES UPDATE UI STATE Main thread UI work Coroutine viewModelScope Network suspend API
While the request runs, the coroutine is parked in a Continuation and the main thread keeps drawing; the result resumes it where it stopped.

Notes

  • suspend is a modifier, not a runtime call. The compiler adds a Continuation parameter and rewrites the body into a state machine. You only call resume() yourself when wrapping a callback API with suspendCancellableCoroutine.
  • A suspend function can only be called from another suspend function or from inside a coroutine.
  • launch returns a Job. You can call job.join() or job.cancel(). It does not give you a value.
  • async returns a Deferred<T>. Call .await() to get the value. await() is itself a suspend function.
  • coroutineScope suspends the caller until all child coroutines finish. If any child throws, the scope cancels the rest and rethrows.
  • supervisorScope isolates children: one child failing does not cancel its siblings. Use it when tasks are independent.
  • withContext(Dispatchers.IO) switches the dispatcher for the block and returns the result to the original context. It is the standard way to change dispatchers inside a suspend chain.
  • viewModelScope uses SupervisorJob() + Dispatchers.Main.immediate and is cancelled when the ViewModel is cleared. lifecycleScope is cancelled when the Lifecycle reaches DESTROYED. In a Fragment, use viewLifecycleOwner.lifecycleScope for work that touches views.
  • Dispatchers.Main.immediate runs the code straight away if you are already on the main thread. Dispatchers.Main always posts it to the main looper first.
  • Avoid GlobalScope. It has no Job, so nothing cancels its coroutines when a screen or ViewModel goes away.
  • withTimeout(5_000) { ... } throws TimeoutCancellationException, a subclass of CancellationException. If it escapes a launch, the coroutine simply ends as cancelled, with no crash and no log. Catch it where you need to react, or use withTimeoutOrNull, which returns null instead.

Code example

This ViewModel shows the standard pattern: a suspend repository call wrapped in withContext(Dispatchers.IO), launched from viewModelScope, and the result posted to a StateFlow.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import java.io.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
 
data class User(val id: String, val name: String)
 
interface UserApi {
    fun getUser(id: String): User // a blocking call
}
 
// Repository: the only place that touches the network or DB
class UserRepository(private val api: UserApi) {
    // main-safe: callers can use it from the main thread
    suspend fun fetchUser(id: String): User =
        withContext(Dispatchers.IO) {  // run the blocking call on the IO pool
            api.getUser(id)
        }
}
 
class UserViewModel(private val repo: UserRepository) : ViewModel() {
 
    private val _user = MutableStateFlow<User?>(null)
    val user: StateFlow<User?> = _user.asStateFlow()
 
    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()
 
    fun loadUser(id: String) {
        viewModelScope.launch {          // runs on Dispatchers.Main.immediate
            try {
                _user.value = repo.fetchUser(id)
            } catch (e: CancellationException) {
                throw e                  // never swallow cancellation
            } catch (e: IOException) {
                _error.value = "Could not load the user"
            }
        }
    }
}
  • withContext(Dispatchers.IO) is the dispatcher switch; the rest of the code in launch stays on the main thread, so writing to the StateFlow is safe.
  • viewModelScope.launch creates a child Job under the ViewModel's SupervisorJob, so it is cancelled when the ViewModel is cleared.
  • The catch for CancellationException comes first and rethrows it. The IOException branch then handles only real network errors.

Run the idea in plain Kotlin

launch returns at once, two async calls run at the same time, and coroutineScope waits for its child before returning.

import kotlinx.coroutines.*

suspend fun fetchName(): String {
  delay(200)
  return "Ada"
}

suspend fun fetchScore(): Int {
  delay(300)
  return 42
}

fun main() = runBlocking {
  val start = System.currentTimeMillis()

  val job = launch {
      delay(100)
      println("launch: side task done")
  }
  println("launch returned a Job immediately")

  val name = async { fetchName() }
  val score = async { fetchScore() }
  println("async started two calls")
  println("result: " + name.await() + " " + score.await())
  val elapsed = System.currentTimeMillis() - start
  println("ran in parallel: " + (elapsed < 450))

  job.join()
  val value = coroutineScope {
      launch {
          delay(50)
          println("coroutineScope child finished")
      }
      "block value"
  }
  println("coroutineScope returned: " + value)
}

Expected output:

launch returned a Job immediately
async started two calls
launch: side task done
result: Ada 42
ran in parallel: true
coroutineScope child finished
coroutineScope returned: block value

The two calls take 200 ms and 300 ms but finish together after about 300 ms, not 500 ms. coroutineScope returns its value only after its child has printed.

In production

Leaked network calls after screen rotation
  • Crashlytics showed IllegalStateException: Fragment not attached to a context after users left a screen during a slow load.
  • The Fragment called GlobalScope.launch { val data = api.fetch(); render(data) }. The coroutine outlived the Fragment.
  • When the response arrived, render called requireContext() on a detached Fragment and crashed.
The fix
  • Moved the call into a ViewModel with viewModelScope.launch, exposed the result as a StateFlow, and so also kept the result across rotation.
  • The Fragment collects it with viewLifecycleOwner.lifecycleScope.launch and repeatOnLifecycle(Lifecycle.State.STARTED), so collection stops when the view is destroyed.
  • No coroutine started by the Fragment can outlive its view any more.
Polling loop spinning after the screen closed
  • Battery reports showed a CPU core busy at 100% after users left a live-scores screen.
  • The loop was while (true) { runCatching { scores.value = api.poll(); delay(5_000) } } in viewModelScope.
  • When the ViewModel was cleared, delay threw CancellationException, runCatching caught it, and the loop went round again. Every later delay threw at once, so the loop spun without pausing.
The fix
  • Replaced runCatching with try / catch (e: IOException) so cancellation is no longer caught.
  • Moved delay(5_000) outside the try and changed the loop to while (isActive).
  • Added a unit test with runTest that cancels the scope and checks the fake API is not called again.

Common mistakes

  • Creating your own scope and never cancelling it. CoroutineScope(Dispatchers.IO).launch { ... } in a class has no owner, so nothing cancels it when the screen goes away. Launch from viewModelScope or lifecycleScope, or cancel your own scope when its owner ends.
  • Using async where launch is enough. If you never need the value, async only adds a Deferred you have to remember to await. Use async when you need results, typically to run calls in parallel and combine them with await or awaitAll.
  • Switching threads with a raw Thread or Executor. That work is outside the Job hierarchy, so cancellation never reaches it. Use withContext(Dispatchers.IO) so the work belongs to the calling coroutine.
  • Swallowing CancellationException with runCatching or a catch-all. The coroutine stays cancelled, but your code carries on as if it were not: it writes state, logs a fake error, or loops. Catch specific exceptions, or rethrow CancellationException first.
  • Using GlobalScope in a ViewModel. GlobalScope lives as long as the process. The coroutine survives ViewModel clearing and keeps the ViewModel reachable until it finishes. Use viewModelScope instead.
  • Calling withContext(Dispatchers.Main) inside a ViewModel. viewModelScope already runs on Dispatchers.Main.immediate. Switching to Dispatchers.Main posts the block to the main looper for nothing. Switch away to IO or Default only for the work that needs it.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What does the suspend keyword actually do at compile time?”

“When do you use async instead of launch?”

“What is the difference between coroutineScope and supervisorScope?”

“Why must CancellationException be rethrown?”

Quiz

What does the Kotlin compiler add to every suspend function?

Which builder returns a Deferred<T>?

What happens to sibling coroutines in a coroutineScope when one child throws?

Why is runCatching around a suspend call risky?

0 of 4 answered

Mini task

15-minute exercise: convert a blocking call to a suspend + builder pattern

You have a legacy function in a ViewModel that calls a blocking Retrofit API on the main thread.

  1. Open your project and find a ViewModel that calls a blocking repository method directly from a click handler. If you do not have one, create a FakeRepo with a fun getUsers(): List<User> that calls Thread.sleep(3_000) and returns a list.

  2. Change the repository method to suspend fun getUsers(): List<User> and wrap the blocking call in withContext(Dispatchers.IO) { ... }.

  3. In the ViewModel, call the new suspend function from viewModelScope.launch { ... }. Store the result in a MutableStateFlow<List<User>> and expose it as a read-only StateFlow. Add Log.d("Users", "updating state") just before you write the result.

  4. In a composable, collect the StateFlow with collectAsStateWithLifecycle(). In a View-based screen, collect inside repeatOnLifecycle(Lifecycle.State.STARTED). Show the list.

  5. Start a load, then press Back to leave the screen before the 3 seconds are up, so the ViewModel is cleared. The sleep itself is not interrupted, but withContext checks for cancellation when its block returns and throws CancellationException, so the log line never prints.

Done condition: the UI shows the list without freezing, the sleep runs on a background thread, and "updating state" does not appear when you leave the screen during a load.

Next: Dispatchers and threading