Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 134 ยท Coroutines

Suspend Functions

Understand Kotlin suspend functions - the suspend keyword, calling rules, sequential code that waits, suspending lambdas, blocking versus suspending, withContext and what the compiler does under the hood.

A suspend function is a function that is allowed to pause. That is the whole definition, and it is the heart of Kotlin coroutines. When a suspend function reaches a point where it must wait, it does not block its thread: it saves where it is, hands the thread back, and later continues from the same place. To the code that calls it, nothing special happens. The call simply takes a while, and the next line runs after it.

In the previous lesson you met the idea. Here we look at the rules of the suspend keyword, what you can and cannot do with it, the most common mistake (blocking inside a suspend function), and what the compiler does for you. The next lesson covers the coroutine builders that start work concurrently.

Declaring and calling

Put suspend before fun. A suspend function looks like any other function: parameters, a return type, a body. It may call other suspend functions, including the library ones such as delay.

Kotlin A suspend function and its caller

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.

Every call to a suspend function is a possible suspension point: a place where the coroutine may pause and resume later. Your IDE marks these with an arrow icon in the gutter. Code between two suspension points runs normally and without interruption.

The calling rule

A suspend function can only be called from:

  • another suspend function,
  • the body of a coroutine builder lambda such as runBlocking { ... }, launch { ... } or async { ... },
  • a suspending lambda (a lambda whose function type is marked suspend).

An ordinary function does not have the context a suspension needs. Here is a classic surprise: a normal lambda stored in a variable is not suspending, even inside a coroutine.

Kotlin Suspend call in a plain lambda (fails on purpose)

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.

The compiler stops at the delay call with error: suspension functions can only be called within coroutine body. The lambda { ... } has the ordinary type () -> Unit, and runBlocking's own scope does not extend into it. The fix is to declare the lambda's type as suspend () -> Unit:

Kotlin A suspending lambda

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.

Function types with suspend are how libraries accept code that may wait: the lambda you pass to launch, async or withContext is such a type, and so is the lambda inside flow { ... } (see flows). Inline functions like forEach, map and repeat are an exception in the other direction: because they are inlined, you may call suspend functions inside their lambdas without extra work (see inline functions).

Sequential by default

Suspend functions run one step after another, like any code. If one call needs the result of the previous one, that is exactly what you want. But watch the cost when the steps are independent:

Kotlin Sequential calls add up

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.

Two calls of 200 ms each take at least 400 ms, one after the other, even though neither needs the other. We print a comparison instead of the actual time because timings differ from run to run. To run independent calls at the same time, use async (see coroutine builders). A suspend function by itself never creates concurrency; it only makes waiting possible without blocking.

Suspending is not blocking, and not background

Two misconceptions are worth killing early.

  1. suspend does not move work to another thread. A suspend function that does a heavy calculation still runs on the calling thread and blocks it. Suspension only happens at a real suspension point such as delay, a channel operation or withContext.
  2. Blocking calls inside a suspend function still block. Thread.sleep, reading a file with plain Java IO, or a long loop hold the thread. In a single-thread scope, everyone else waits.
Kotlin Blocking versus suspending

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 first part the helper cannot start until main gives up the thread with yield(), so "main after sleep" comes first. In the second part delay frees the thread, the helper runs, and only then does the main coroutine continue. If you must call blocking code, move it to another dispatcher with withContext(Dispatchers.IO) (see dispatchers and context).

withContext: switching where code runs

withContext(context) { ... } is a suspend function that runs a block in another context (usually another dispatcher) and returns its result. The calling coroutine suspends until the block completes. It is the standard way to make a function "main-safe": callers do not need to know that the function does blocking work inside.

Kotlin A main-safe function with withContext

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.

The function checksum has the right shape for a library API: it is suspend, it chooses its own dispatcher, and the caller can call it from any coroutine without worrying about blocking.

Exceptions and return values

A suspend function returns a value or throws, exactly like a normal one. You handle failures with try/catch around the call. There is no separate error channel as in callback APIs.

Kotlin try/catch around a suspend call

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.

One thing to remember for later: never catch CancellationException and swallow it, because that exception is how cancellation travels through suspend functions (see cancellation).

What the compiler does

You do not need this to use coroutines, but it removes the magic. For every suspend function the compiler adds one hidden parameter, a continuation: an object that remembers "what to do next". The body is rewritten into a state machine: each suspension point is a numbered state, and local variables are saved in the continuation object. When delay suspends, the function returns a special marker value to its caller. When the timer fires, the continuation's resumeWith is called, and the machine jumps to the saved state. This is why a Java caller sees Object loadGreeting(String, Continuation<? super String>), and why suspend functions cannot be called from Java directly.

The consequences you notice as a developer: a suspend function call costs a little more than a plain call, a suspension that does not actually suspend (the value is ready) costs very little, and stack traces of suspended code look different from plain ones because the original stack was unwound at the suspension.

Design tips

  • Give a suspend function a name that describes the result, as for any function: loadUser, not loadUserAsync. The suspend keyword already tells callers it may wait.
  • Make suspend functions main-safe: use withContext inside for blocking or CPU-heavy parts.
  • Do not make a function suspend if it never suspends; it forces every caller into a coroutine for no reason.
  • Prefer returning results over passing callbacks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the suspend modifier allow a function to do?

    suspend lets the function pause at suspension points and be resumed later. It does not change the thread by itself.
  2. 2. Why does a plain lambda val f = { delay(10) } not compile?

    Suspension requires a suspend context. An ordinary function type has none, even if the lambda is written inside a coroutine.
  3. 3. A suspend function calls Thread.sleep(500). What happens?

    Thread.sleep is a blocking call. suspend does not change that, so the thread stays occupied.
  4. 4. Two independent suspend calls written one after the other, each taking 200 ms, take about:

    Suspend functions run sequentially by default. Use async to overlap independent calls.
  5. 5. What is withContext(Dispatchers.Default) { ... } typically used for?

    withContext switches context, suspends the caller until the block finishes, and returns the block's value.

Summary

  • suspend marks a function that can pause without blocking its thread.
  • Suspend functions can be called only from coroutines, other suspend functions or suspending lambdas.
  • They run sequentially by default; concurrency comes from builders such as launch and async.
  • suspend does not mean background: blocking code inside still blocks, and withContext is how you move it.
  • Errors are ordinary exceptions handled with try/catch; do not swallow CancellationException.
  • The compiler rewrites suspend functions into state machines with a hidden continuation parameter.

Next: Coroutine Builders