Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 134 ยท Coroutines

Flows

Learn Kotlin Flow - the flow builder, collect, cold streams, operators like map, filter and take, error handling with catch, buffer, flowOn, zip, combine and flatMapMerge, with runnable examples.

A suspend function returns one value, later. But many things in programs are sequences of values that arrive over time: progress updates of a download, lines read from a file, readings from a sensor, results from a search as you type. A List holds all values at once, which is wrong for something that is still happening. A Flow<T> is Kotlin's type for this: an asynchronous stream of values, computed on demand, with suspending code inside.

If you know Sequence, think of a flow as the same idea with suspend allowed everywhere. If you know channels, think of a flow as a stream built on top of them, with a friendlier API and automatic cleanup. This lesson builds on channels and sequences, and leads to StateFlow and SharedFlow.

Your first flow

You create a flow with the flow { } builder. Inside it you call emit(value) to produce values, and you may suspend (with delay, network calls, anything). You consume it with collect { }, which is a suspend function that runs until the flow completes.

Kotlin flow builder and collect

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 function countdown is not marked suspend: building a flow does nothing yet. The code in the flow { } block runs only when somebody collects, and it runs in the collector's coroutine.

Flows are cold

A flow is cold: it is a recipe, not a running process. Every call to collect starts the recipe again from the beginning, so two collectors get two independent runs.

Kotlin Cold flows run per collector

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.

flow started appears twice. This is a feature: no resource is used until someone is interested, and a stream that nobody reads costs nothing. Its price: if starting the flow is expensive (a network request), each collector pays for it. When several collectors should share one running source, you need a hot flow, which is the subject of the next lesson.

Making flows from values

You do not always need the builder. Quick ways to get a flow:

Kotlin flowOf and asFlow

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.

Operators: transforming a flow

Like collections, flows have map, filter, take, onEach and more. Intermediate operators return a new flow and do nothing until a terminal operator such as collect runs. The lambdas may suspend.

Kotlin Intermediate operators

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.

After three values take(3) cancels the upstream flow, so 7*7 and 9*9 are never computed. Cancellation by an operator works through the same CancellationException you saw in cancellation.

Other operators worth knowing:

  • transform { }: emit zero, one, or many values per input (the general one).
  • takeWhile, drop, dropWhile, distinctUntilChanged, withIndex.
  • scan/runningFold: running results, like on lists.
  • debounce, sample: time-based thinning of values (useful for search-as-you-type).
Kotlin transform and scan

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.

Terminal operators

A terminal operator starts the collection and produces a result: collect, toList, toSet, first, firstOrNull, single, count, reduce, fold.

Kotlin Terminal operators

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.

first stops collecting as soon as it has its answer, which cancels the upstream; toList and fold must wait for the end. An infinite flow with toList() never returns, just like generateSequence { } with toList().

Context: flowOn

A flow runs in the context of its collector. If the producer does heavy work (parsing, disk), you want that on another dispatcher but the collector (a UI, say) on its own. The operator flowOn changes the context of everything above it, and only that:

Kotlin flowOn moves the upstream

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.

Emission happened on the pool and collection on main. Do not switch context inside flow { } with withContext. Flows must preserve the context of the collector, and the library checks this:

Kotlin withContext inside flow (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 result is an IllegalStateException that starts with Flow invariant is violated and tells you to use flowOn instead. The rule exists so that a collector can always rely on its values being delivered in its own context. (Use channelFlow if you really must emit from several coroutines.)

Backpressure: buffer and conflate

By default, producer and collector run sequentially in one coroutine: the next value is produced only after the collector has handled the previous one. The total time is the sum of both. If they could overlap, the work would be faster. buffer() runs the producer in a separate coroutine connected by a channel:

Kotlin buffer lets the producer run ahead

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.

Without buffer each "produced" line follows the previous "consumed". With buffer, all three values are produced while the first is still being consumed. If the collector is slow and you only care about the newest values, conflate() drops intermediate ones, and collectLatest { } cancels the processing of the previous value when a new one arrives:

Kotlin conflate and collectLatest

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.

With conflate, values 2 and 3 were dropped while the collector was busy with 1; it then took the newest value waiting (4), and finally 5. With collectLatest, nothing is dropped but only the last value gets a done line, because every earlier block was cancelled in the middle of delay(100). This is what you want for "load details of the selected item": when the selection changes, drop the old request.

Combining flows

zip pairs the n-th value of one flow with the n-th of another. combine emits whenever either flow emits, using the latest value of each.

Kotlin zip and combine

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.

zip produced three pairs. combine printed 2=one, 3=one, 3=two and 3=three: it waited until both flows had a value (by then the numbers had already reached 2), and from then on each new value of either flow was paired with the latest value of the other. After numbers finished, letters kept emitting and was paired with the last number, 3. The first combined value appears only once both flows have emitted at least once.

Flattening: flatMapConcat, flatMapMerge, flatMapLatest

When each value starts another flow (a request per search term), you must say how to combine the inner flows. These three operators differ in concurrency.

Kotlin flatMapConcat vs flatMapMerge

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.

flatMapConcat finishes the whole inner flow of 1 before it starts 2: results arrive in order but sequentially. flatMapMerge runs the inner flows at the same time, so the "first" lines come out together, and then the "second" ones; the total is faster but order is by arrival. flatMapLatest is the third option: a new value cancels the inner flow of the previous one.

Errors and completion

Exceptions thrown in the producer, in an operator or in the collector travel to the collector's try/catch. The operator catch { } handles errors from the upstream (everything above it) and can emit a fallback value. onCompletion { } is like finally and receives the error, or null.

Kotlin catch 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.

Position matters: catch is transparent, it affects only what is above it. Errors thrown inside collect { } are not seen, so wrap the collection in a try/catch, or move the logic into onEach { } before the catch. Note that catch ends the failed stream; it can emit a replacement, but cannot make the producer carry on.

Launching a flow in a scope

collect suspends the caller until the flow is complete. To run collection in the background, write flow.onEach { ... }.launchIn(scope), which returns a Job. This is the usual way to "subscribe" to a flow in a long-living object.

Kotlin launchIn

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.

launched, main goes on is printed first because launchIn does not wait. Cancel the returned job (or the scope) to stop the subscription.

When to use a flow

  • Flow for streams that go through operators: a sequence of results, updates from a database, events. Cold, one collector per run.
  • suspend function for a single result.
  • Sequence for synchronous lazy computations that never suspend.
  • Channel for hand-over between coroutines and work queues.
  • StateFlow / SharedFlow for hot state and event broadcasting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean that a flow is cold?

    A cold flow is a recipe: nothing happens until it is collected, and each collector triggers a fresh run.
  2. 2. In flow.flowOn(Dispatchers.Default).collect { }, which code runs on Dispatchers.Default?

    flowOn changes the context of the upstream flow; the collector keeps its own context.
  3. 3. Which operator cancels the processing of the previous value when a new value arrives?

    collectLatest restarts the block for the newest value and cancels the one still running.
  4. 4. A catch { } operator is placed before collect { }. The collect lambda throws. Does catch handle it?

    catch is transparent downstream. Exceptions from the collector need an ordinary try/catch around the collection.
  5. 5. Why is withContext(Dispatchers.Default) { emit(x) } inside flow { } an error?

    The flow invariant requires emissions in the collector's context. flowOn is the correct way to move upstream work.

Summary

  • Flow<T> is an asynchronous, cold stream: the builder runs on each collect.
  • Create flows with flow { emit() }, flowOf, asFlow; transform them with map, filter, take, transform, scan.
  • Terminal operators (collect, toList, first, fold) start the work; take and first cancel the upstream.
  • flowOn moves the upstream to another dispatcher; never use withContext inside flow { }.
  • buffer, conflate and collectLatest handle slow collectors; zip, combine and flatMap* combine flows.
  • catch handles upstream errors only; onCompletion acts like finally; launchIn collects in the background.

Next: StateFlow and SharedFlow