suspend Functions and Continuations

suspend Functions and Continuations in Kotlin: --- A benefits office has one caseworker at the desk and a deep tray of client folders.


The Analogy: The Caseworker's Folder and Its Bookmark

A benefits office has one caseworker at the desk and a deep tray of client folders. Each application is a sequence of steps -- verify identity, tally income, apply allowances, compute the award -- and some of those steps cannot be finished on the spot because a document has not yet arrived in the post. A bank statement is missing, or an employer's letter is still coming. The step is reached, but it cannot be completed until the paper turns up.

The caseworker never sits idle staring at the tray waiting for the postman. When they reach a step that needs a document that has not arrived, they do something precise: they draw a bookmark line across the worksheet at exactly the step they reached, and they write down every running figure beside it -- the income tallied so far, which allowances have already been applied, the partial award. Then they slide that folder into a pending shelf and pick up the next folder. The desk keeps moving; only the one blocked application is set aside, and it is set aside with its state fully recorded.

When the missing document finally arrives, a mail clerk drops it onto the matching folder and returns the folder to the desk. The caseworker reopens it, reads the bookmark line to see exactly which step they had reached, reads the recorded figures to restore every running total, and carries straight on from that step as though no interruption had happened. They do not reread the whole file from the top, and they do not recompute the totals. The folder itself carries everything needed to resume: the place to continue, and the values to continue with. The folder is the resumable state made physical.

The failure is the caseworker who keeps the running figures in their head instead of writing them on the worksheet. The first time a document is missing and they set the folder aside, the totals evaporate. When the folder comes back they have lost their place; at best they must start the whole file again, at worst they resume from a half-remembered figure and approve an award that is simply wrong. The bookmark and the recorded figures are precisely what make pausing a task safe. Without them, a paused computation is not paused -- it is corrupted. Everything a coroutine does to suspend and resume is the discipline of always writing the figures on the folder.


Syntax or Core Structure

A suspend function is one the compiler allows to pause at certain points and resume later without blocking a thread. You write it in ordinary top-to-bottom style -- no callbacks, no nesting -- and each call to another suspend function is a place where the coroutine may bookmark itself and step away. A suspend function can only be called from another suspend function or from a coroutine builder such as runBlocking, because only those provide the folder the state is written into.

import kotlinx.coroutines.*

suspend fun steep(seconds: Int): String {
    delay(seconds * 10L)          // a suspension point: bookmark and step away
    return "steeped " + seconds + "s"
}

fun main() = runBlocking {
    println("start")
    val result = steep(3)         // reads like a normal call, yet it suspended
    println(result)
    println("done")
}

Output:

start
steeped 3s
done

The body of main reads exactly like ordinary sequential code: print, call, print, print. There is no visible callback anywhere, yet at the delay inside steep the coroutine bookmarked itself, released the thread for ten milliseconds, and resumed to compute the return value. That direct style is the entire point of suspend: you write the steps in the order they happen, and the compiler quietly rewrites them into the pause-and-resume machinery. The word suspend on steep is what gives it permission to call delay; strip that modifier and the call to delay would not compile, because a plain function has no folder to write its bookmark on.


Technical Depth: Continuations and the State Machine

The anatomy of a suspending call

Behind the direct style, the compiler rewrites every suspend function into a state machine. Each suspension point becomes a state; the function gets a hidden Continuation parameter; and any local variable that must survive across a suspension is stored on that continuation. These are the pieces, and each one is a part of the caseworker's folder.

ConceptWhat it isFolder equivalent
suspend modifiermarks a function that may pausea task that may need a missing document
suspension pointa call that can pause the coroutinereaching a step that needs the document
Continuationobject holding the resume label and saved localsthe folder with its bookmark and figures
resumeWithhands a result or error back to resumethe document arrives, work continues at the mark

The crucial consequence is that locals are not lost when a coroutine suspends. The compiler lifts every variable that is read after a suspension point into the continuation object, so that resuming restores them exactly. This is the caseworker writing the running figures on the worksheet rather than trusting memory.

import kotlinx.coroutines.*

suspend fun accumulate(): Int {
    var total = 0
    for (n in 1..3) {
        total += n
        println("after adding " + n + ", total = " + total)
        delay(10L)                 // suspends mid-loop; total must survive
    }
    return total
}

fun main() = runBlocking {
    println("final: " + accumulate())
}

Output:

after adding 1, total = 1
after adding 2, total = 3
after adding 3, total = 6
final: 6

The loop suspends on delay three separate times, and each time the local total is preserved across the pause. The printed totals climb 1, 3, 6 because the continuation carried total and n through every suspension. Nothing was recomputed from the top; the state resumed exactly where it left off, and the final return is 6.

Seeing the continuation directly

Most of the time the continuation is invisible, but suspendCoroutine hands it to you so you can bridge a callback-based API into the suspend world. You receive a Continuation, and calling resume on it is precisely the document arriving and the folder continuing.

import kotlin.coroutines.*
import kotlinx.coroutines.*

suspend fun awaitValue(): Int = suspendCoroutine { cont ->
    // A real bridge would register a callback; here we resume at once.
    cont.resume(42)
}

fun main() = runBlocking {
    println("before")
    val v = awaitValue()
    println("got " + v)
}

Output:

before
got 42

The lambda receives cont, the continuation for the suspended awaitValue call. Calling cont.resume(42) is the explicit form of what delay does implicitly: it delivers a result to the bookmarked coroutine and lets it carry on, so v becomes 42 and "got 42" prints. In production you would call resume from inside some other API's callback -- when a network reply lands, when a file finishes reading -- which is exactly how sequential-looking suspend code sits on top of genuinely asynchronous machinery.

Suspension is possible, not guaranteed

A suspend function only pauses if it actually reaches a suspension point. If an early return fires first -- a cache hit, a validation short-circuit -- the function completes immediately without ever bookmarking itself. The suspend modifier grants the possibility of pausing; it does not force it.

import kotlinx.coroutines.*

suspend fun lookup(cache: Map<Int, String>, id: Int): String {
    val hit = cache[id]
    if (hit != null) return hit    // returns without ever suspending
    delay(50L)                     // only the miss path reaches a suspension
    return "loaded" + id
}

fun main() = runBlocking {
    val cache = mapOf(1 to "cached-one")
    println(lookup(cache, 1))      // hit: no suspension at all
    println(lookup(cache, 2))      // miss: suspends on delay
}

Output:

cached-one
loaded2

The first call finds id 1 in the cache and returns "cached-one" before the delay line is ever reached, so that call never suspends. The second call misses, falls through to delay, bookmarks itself, and resumes to return "loaded2". The same suspend function took a non-suspending fast path once and a suspending slow path once. This is why marking a rarely-suspending function suspend is cheap on the hit path: no state machine work happens unless a suspension point is actually crossed.


Real World Example: Building a User Profile

This program assembles a user profile from two pieces of data, each fetched by its own suspend function that models a slow network call with a delay. The top-level buildProfile reads as plain sequential code -- fetch the name, fetch the score, combine them -- which is exactly the readability that suspend buys.

import kotlinx.coroutines.*

suspend fun fetchName(id: Int): String {
    println("fetching name...")
    delay(100L)
    return "user" + id
}

suspend fun fetchScore(id: Int): Int {
    println("fetching score...")
    delay(100L)
    return id * 10
}

suspend fun buildProfile(id: Int): String {
    val name = fetchName(id)      // suspends 100ms
    val score = fetchScore(id)    // then suspends another 100ms
    return name + " scored " + score
}

fun main() = runBlocking {
    println("building profile for 7")
    println(buildProfile(7))
}

Output:

building profile for 7
fetching name...
fetching score...
user7 scored 70

The output traces the sequential structure directly. main prints its banner, then enters buildProfile, which calls fetchName first: "fetching name..." prints, the coroutine suspends for 100 ms, and name becomes "user7". Only after that fully completes does fetchScore begin, print "fetching score...", suspend another 100 ms, and return 70.

The two fetches happen strictly one after the other, which is why "fetching name..." always precedes "fetching score...". The final line combines the two results into "user7 scored 70". Every value is deterministic: the id is fixed at 7, so the name is "user7" and the score is 7 times 10.

The direct style is genuinely valuable here. Compare this to the callback-nested version the same logic would require without suspend: fetch the name, and inside its callback fetch the score, and inside that callback combine them. The suspend version reads as three plain lines, and the continuation machinery preserves name across the second suspension so the final concatenation has both values.

The real design flaw is that fetchName and fetchScore are independent -- each needs only id, and neither depends on the other's result -- yet they run sequentially, so the total wait is 100 plus 100, a full 200 milliseconds. Because they do not depend on each other, they could overlap and finish in roughly 100 milliseconds total. Writing them sequentially wastes half the time for no reason. The fix is to launch both as concurrent async computations and await them together, which is the subject of the next lesson; sequential suspension is the right tool only when each step truly needs the previous step's result.


Common Mistakes

  1. Calling a suspend function from ordinary code. A suspend function needs a continuation, which only another suspend function or a coroutine builder provides. Calling one from a plain function does not compile. Wrap the call in runBlocking, coroutineScope, or make the caller suspend too.
  1. Believing suspend makes code run in the background. The modifier only grants permission to pause; it does not add concurrency. A suspend function called directly runs sequentially, in order, on the same coroutine. Concurrency comes from launch and async, not from suspend.
  1. Blocking inside a suspend function. Calling Thread.sleep or a blocking I/O call inside a suspend function defeats the purpose: the thread is held, not released. Use suspending equivalents so the coroutine actually steps away at the wait.
  1. Running independent steps sequentially. Awaiting two unrelated suspend calls one after another doubles the latency for nothing. If neither depends on the other, run them concurrently with async and combine the results.
  1. Assuming a suspend function always suspends. Suspension is possible, not guaranteed. If no suspension point is actually reached -- a cache hit returns before any delay -- the function simply returns directly, like any other call.
  1. Losing state by using shared mutable variables instead of locals. Locals are saved on the continuation and restored on resume. Reaching for shared top-level state to carry values across a suspension invites races and loses the safety the continuation gives you for free.
  1. Forgetting that exceptions travel through the continuation. An exception thrown after a suspension point propagates to the caller through resumeWith, just like a normal throw. Do not assume suspended code cannot throw back into your try.
  1. Marking a function suspend that never suspends. Adding suspend to a function with no suspending calls only restricts who can call it, with no benefit. Keep the modifier for functions that genuinely have a suspension point.
  1. Calling resume on a continuation twice. A continuation from suspendCoroutine must be resumed exactly once. Resuming it a second time throws IllegalStateException, because the folder has already left the desk.

Best Practices

  • Write suspend functions in plain sequential style; let the compiler turn the direct code into the pause-and-resume state machine.
  • Give a function the suspend modifier only when it actually reaches a suspension point, so the signature tells the truth about what it does.
  • Keep values you need across a suspension in locals, not shared state, so the continuation preserves them safely.
  • Run independent suspend calls concurrently with async; reserve sequential calls for steps that genuinely depend on the previous result.
  • Never block a thread inside a suspend function; use suspending I/O and delay so the coroutine yields at every wait.
  • When bridging a callback API with suspendCoroutine, resume the continuation exactly once, on both the success and the error path.
  • Prefer suspendCancellableCoroutine over suspendCoroutine for real bridges, so a cancelled coroutine can stop waiting on the callback.
  • Let exceptions from suspend calls propagate normally; handle them with ordinary try/catch around the suspending call site.

Practice Exercises

  1. Write suspend fun boilWater() and suspend fun steepTea(), each printing a line and delaying, then a suspend fun makeTea() that calls them in order. Call makeTea from a runBlocking main and predict the exact output order.
  1. Write a suspend function with a loop that builds a running product across three delay calls, printing the product each iteration. Confirm the local survives every suspension by checking the printed values against a hand trace.
  1. Use suspendCoroutine to write awaitDoubled(n: Int) that resumes with n * 2. Call it from runBlocking, then add a second cont.resume call and observe the exception it throws.
  1. Take the sequential buildProfile from this lesson and describe, in a comment, exactly which two lines would change to run the fetches concurrently, and why that cuts the total wait roughly in half.