Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 134 ยท Practice

Practice Problems: Coroutines and Flow

Seven hands-on Kotlin exercises on coroutines, timeouts, channels, flows, cancellation cleanup and concurrency limits, each with a runnable solution and an explanation.

Reading about coroutines gives you the vocabulary; solving small problems gives you the reflexes. This lesson has seven exercises that cover the parts of concurrent Kotlin people most often get wrong: running work in parallel, giving up after a deadline, passing values through channels, building flow pipelines, cleaning up after cancellation, limiting concurrency and retrying failures.

Each exercise follows the same pattern. Read the task, close the page, and try to write it yourself in a scratch file. Then open the solution, run it, and compare. The solutions are complete programs, so you can change a number and watch the output change. If a concept feels shaky, the links point to the lesson that teaches it: coroutines intro, builders, cancellation, channels and flows.

flowchart LR
    A["Read the task"] --> B["Write your own solution"]
    B --> C["Run it and compare the output"]
    C --> D{"Same result?"}
    D -- yes --> E["Change one requirement and redo it"]
    D -- no --> F["Read the explanation, then retry from scratch"]
    F --> B

Practice loop: attempt first, compare second, and re-solve what you missed.

Exercise 1: parallel lookups

Task. You have five items and a suspend function price(item) that takes 200 ms. Compute the total price of all items so that the whole job takes about 200 ms, not one second. Prove the work ran in parallel without printing the elapsed time (it changes from run to run).

Hint. Start every lookup with async first, and only then wait for the results with awaitAll. Mapping and awaiting in the same step makes the lookups run one after the other.

Kotlin Solution 1: async and awaitAll

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.

map { async { ... } } creates all five deferred values before anything is awaited, so the five 200 ms delays overlap. The sequential version items.sumOf { price(it) } would take about a second, and the check prints false for it. Comparing against a loose bound (600 ms) instead of an exact number keeps the check reliable.

Exercise 2: a deadline with a fallback

Task. Write lookup(delayMs) that simulates a call. Ask for a value with a 300 ms deadline. If the call is slower, return the text "cached" instead. Then show what happens when you use the throwing version of the timeout.

Hint. There are two functions: one returns null on timeout, the other throws.

Kotlin Solution 2: withTimeoutOrNull and withTimeout

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.

withTimeoutOrNull returns null when the deadline passes, which pairs naturally with ?:. withTimeout throws TimeoutCancellationException, a subclass of CancellationException. Because it is a cancellation, an uncaught one inside a launch cancels only that coroutine silently, which surprises many people; catch it where you set the deadline. The slow lookup is cancelled at its delay, so it never wastes the full second.

Exercise 3: a two-stage channel pipeline

Task. Build a pipeline of two coroutines connected by channels: the first produces the numbers 1 to 6, the second squares them. The main coroutine sums the squares. Everything must finish cleanly with no leftover coroutines.

Hint. produce starts a coroutine and returns its channel; closing happens automatically when the block ends. Loop over a channel with for (x in channel).

Kotlin Solution 3: produce and consume

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.

When numbers finishes its loop the channel is closed, so the for loop in squares ends; when squares ends, its channel closes and the loop in main ends. Closing flows downstream like a domino. Both producers are children of the runBlocking scope (that is why they are extensions on CoroutineScope), so nothing can leak. Channels have a rendezvous buffer by default, which means the stages run in lockstep; pass a capacity to produce to decouple them.

Exercise 4: a flow pipeline

Task. Create a flow that emits the numbers 1 to 10. Keep the even numbers, square them, and take only the first three results. Print a message when the flow completes. Then compute a running total of the squares with runningFold.

Hint. Operators are applied in order. take cancels the upstream flow as soon as it has enough values, and onCompletion runs at the end whether the flow finished normally or was cut short.

Kotlin Solution 4: filter, map, take and onCompletion

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.

Look at the emitting lines of the first run: they stop at 6, because after the third even number (6) take cancels the producer and the loop never reaches 7. The second run is not cut short, so all ten values are emitted. A flow is cold: nothing happens until a terminal operator such as toList or collect is called, and each call starts the flow from the beginning.

Exercise 5: clean up after cancellation

Task. Start a coroutine that prints working 0, working 1, and so on every 100 ms. After 250 ms cancel it and wait for it to finish. Its finally block must run a cleanup step that itself suspends (it takes 50 ms) and prints cleanup done.

Hint. A cancelled coroutine cannot suspend normally any more: the next delay throws again. Use withContext(NonCancellable) for cleanup that must complete. Use cancelAndJoin, not just cancel, so you know the cleanup is finished.

Kotlin Solution 5: NonCancellable cleanup

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 worker prints three steps (at 0, 100 and 200 ms), then the main coroutine cancels it during the delay of step 2. The CancellationException is thrown at that delay, the finally block runs, and NonCancellable lets its own delay complete. Without it, the 50 ms delay would throw and cleanup done would never print. Keep NonCancellable blocks short and use them only for cleanup such as flushing a file or releasing a lock, never for ordinary work.

Exercise 6: limit how many run at once

Task. Run twelve jobs of 100 ms each, but never more than three at the same time. Record the highest number of jobs that were ever running together and return the results in order.

Hint. A Semaphore(3) hands out three permits; withPermit takes one and always gives it back, even on failure.

Kotlin Solution 6: Semaphore as a concurrency limit

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.

All twelve coroutines start immediately, but only three get past withPermit at a time; the rest suspend (they do not block a thread) until a permit is free. Because runBlocking here uses a single thread, the plain Int counters are safe. On a multi-threaded dispatcher you would need an AtomicInteger or a Mutex, as explained in shared state. The results keep their input order because awaitAll returns values in the order of the list.

Exercise 7: retry and recover in a flow

Task. A flow fails on its first two attempts with an IllegalStateException and succeeds on the third. Make the collector see the data from the successful attempt without writing a retry loop by hand. Then write a second flow that always fails and make it end with the value "fallback" instead of an exception.

Hint. retry(times) { cause -> ... } restarts the upstream flow when its predicate returns true. catch handles upstream exceptions, and inside it you can emit a replacement value.

Kotlin Solution 7: retry and catch

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.

Notice that the collector sees attempt 1 started and attempt 2 started even though those attempts failed: a retry restarts the whole flow, and values already emitted are not taken back. If duplicates would be harmful, design the flow so it emits only after the risky step, or collect into a list first. The predicate also lets you retry only errors that make sense to retry (a timeout, yes; a bug, no). catch only sees exceptions from upstream; an exception thrown inside collect itself is not caught by it.

Going further

Once the seven solutions feel easy, change the requirements:

  • In exercise 1, make one of the five lookups throw. What happens to the other four? Compare coroutineScope and supervisorScope (structured concurrency and coroutine exceptions explain why).
  • In exercise 3, give produce a capacity of 2 and print when each value is sent and received.
  • In exercise 4, collect with buffer() and a slow collector, and compare it with conflate().
  • Write tests for your solutions using the ideas in testing coroutines.
  • Turn exercise 6 into a reusable suspend fun <T, R> List<T>.parallelMap(limit: Int, transform: suspend (T) -> R): List<R>.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does items.map { async { price(it) } }.awaitAll() run lookups in parallel, while items.map { async { price(it) }.await() } does not?

    In the second version each await() suspends the map step until that lookup is done, so the next async only starts afterwards. Starting everything first and awaiting together lets the delays overlap.
  2. 2. A coroutine's finally block needs to call a suspending function after the coroutine was cancelled. What is the standard solution?

    After cancellation, normal suspending calls throw again. withContext(NonCancellable) lets short cleanup work run to completion.
  3. 3. What does take(3) do to the upstream flow once it has received three values?

    take cancels the upstream collection after enough values arrived, which is why the producer stops emitting.
  4. 4. Which statement about retry on a flow is correct?

    retry restarts the whole upstream flow from the start, so earlier emissions have already been seen by the collector. It only reacts to upstream exceptions, and any delay must be added by you.
  5. 5. What does Semaphore(3).withPermit { ... } guarantee?

    A semaphore limits concurrency. Coroutines that cannot get a permit suspend until one is released, and withPermit releases it even when the block throws.

Summary

  • Start all async jobs first, then awaitAll, to run independent work in parallel.
  • withTimeoutOrNull gives a value or null; withTimeout throws TimeoutCancellationException.
  • produce builds channel stages that close downstream automatically and stay inside the parent scope.
  • Flows are cold; take cancels upstream, and onCompletion runs either way.
  • Use cancelAndJoin and withContext(NonCancellable) so cleanup finishes after cancellation.
  • Semaphore.withPermit limits concurrency without blocking threads.
  • retry restarts the whole upstream flow; catch handles upstream errors and can emit a fallback.

Next, test your knowledge of the whole language with the Kotlin interview questions.