Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 134 ยท Coroutines

Coroutine Builders

Learn the Kotlin coroutine builders - launch and Job, async and Deferred, runBlocking, coroutineScope, lazy start, awaitAll and joinAll - and how to run independent work concurrently and combine the results.

A suspend function can wait, but it cannot start work in parallel by itself. To create a new coroutine you use a coroutine builder: a function that takes a lambda and runs it as a coroutine. The three you will use most are runBlocking (the bridge from normal code), launch (start something and do not care about a result) and async (start something and get a result later). A fourth, coroutineScope, groups work inside a suspend function.

This lesson shows each builder with runnable code, what handle each one gives back, and how to combine results. It builds on suspend functions and leads into structured concurrency, which explains why the builders are arranged in a tree.

launch: fire and forget (with a handle)

launch starts a new coroutine and returns immediately with a Job. The Job is a handle to the running coroutine: you can wait for it with join(), cancel it with cancel(), and ask about its state with isActive and isCompleted. It does not carry a result value.

Kotlin launch and Job.join

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 first print after launch happens before the child prints anything, because launch returns at once and the child only runs when the parent suspends. The parent suspends at join(). Without join(), runBlocking would still wait for its child, but only at its closing brace; join() lets you wait at a particular point in the code.

Use launch for work that produces side effects: logging, saving, updating a screen, sending a message. If you need a value back, use async.

async: a result later

async also starts a coroutine immediately, but returns a Deferred<T>, which is a Job that will eventually hold a value of type T. You get the value with await(), which suspends until it is ready. The name comes from the pattern "promise" or "future".

Kotlin async and await

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 two price calls run at the same time, because both async blocks start before the first await. The total wait is about 100 ms, not 200 ms. This is the standard recipe for parallel decomposition: start all independent work with async, then await the results.

A classic mistake is to start and await in the same expression, which makes the work sequential again:

Kotlin Accidentally sequential

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.

For a list of tasks there are two helpers. awaitAll() waits for a collection of Deferred values and returns the list of results in the original order. joinAll() waits for a collection of jobs.

Kotlin awaitAll over a list

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.

Errors in async

If the code inside async throws, the exception is stored and thrown again from await(). But it also cancels the parent, as you will see in structured concurrency. When you want to handle the failure locally, wrap the work in a coroutineScope (below) and put try/catch around the await.

Kotlin The exception surfaces at await (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 program prints started and then ends with Exception in thread "main" java.lang.IllegalStateException: boom and exit code 1. It is the await() that rethrows. The following version handles it:

Kotlin Catching the failure around coroutineScope

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.

runBlocking: the bridge

runBlocking is the only builder that blocks the calling thread. Use it in main and in tests, and almost nowhere else. Calling it from inside a coroutine blocks a dispatcher thread and defeats the purpose of suspending. It returns the value of its lambda:

Kotlin runBlocking returns a value

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.

coroutineScope: a group inside a suspend function

coroutineScope { ... } is a suspend function, not a blocking one. It creates a scope, runs the block, and returns only when all coroutines started inside it have finished. It is the standard way to start concurrent work inside a suspend function without leaking it:

Kotlin Concurrent work inside a suspend function

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.

loadProfile looks like a normal suspend function from the outside, and it is concurrent inside. If one of the children fails, the scope cancels the other and rethrows the failure.

Lazy start

By default a builder starts the coroutine at once. Pass start = CoroutineStart.LAZY and it starts only when you call start(), join() or await(). This is occasionally useful when the result may not be needed.

Kotlin CoroutineStart.LAZY

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.

Choosing the builder

You want Use
Call suspend code from main or a test runBlocking
Start background work, no result needed launch
Start work and get a value later async + await
Group concurrent work inside a suspend function coroutineScope
Switch dispatcher and wait for the result withContext

Another common mistake is using launch when you need a result and sharing a variable to carry it out. That is racy and clumsy; async exists for that. And do not write async { ... }.await() in a row: if you do not need concurrency, just call the suspend function directly.

The type of a builder's result tells you what you can do with it. If the compiler says Job where you expected Int, you used launch and needed async.

Kotlin Launch does not return a value (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 answers error: initializer type mismatch: expected 'Int', actual 'Job'. The fix is val n: Int = async { 6 * 7 }.await() or, better, plain val n = 6 * 7 when no concurrency is needed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which builder returns a value you can get later with await()?

    async returns a Deferred<T>. launch returns a Job without a result.
  2. 2. How long do val a = async { slow() } and val b = async { slow() }, followed by a.await() and b.await(), take if slow() delays 100 ms?

    Both coroutines are started before the first await, so their delays overlap.
  3. 3. Where does an exception thrown inside async surface for the caller?

    The exception is stored in the Deferred and rethrown by await().
  4. 4. What is special about coroutineScope?

    coroutineScope is a suspend function that waits for its children, and propagates their failures.
  5. 5. Which is the right place to use runBlocking?

    runBlocking blocks the calling thread. It belongs at the very edge of the program, not inside coroutine code.

Summary

  • runBlocking blocks the thread and bridges normal code into coroutines; use it in main and tests only.
  • launch starts work and returns a Job; use join() to wait, cancel() to stop.
  • async returns a Deferred<T>; start all independent work first, then await() (or awaitAll()).
  • Exceptions inside async are rethrown by await().
  • coroutineScope groups concurrent work inside a suspend function and waits for all of it.
  • CoroutineStart.LAZY delays the start until it is needed.

Next: Structured Concurrency