Flows
suggest changeA suspending function returns a single value. When you need a stream of values produced over time (rows from a database, messages from a socket, UI state changes, sensor readings) you use Flow<T> from kotlinx.coroutines.
A Flow is the asynchronous counterpart of a Sequence: it is lazy and computes values on demand, but the code producing values can suspend (call delay, do network I/O, etc.) without blocking a thread.
This article covers:
- creating flows with
flow { },flowOfandasFlow - intermediate and terminal operators
- why flows are cold and sequential
- changing the execution context with
flowOn - buffering, conflation and
collectLatest - combining and flattening flows
- error handling, completion and retries
- cancellation and
launchIn - hot flows:
StateFlow,SharedFlow,stateInandshareIn - turning callback APIs into flows with
callbackFlow
All examples use this dependency:
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}
and these imports:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
A first flow
The flow { } builder creates a flow. Inside it, emit(value) sends a value downstream. Nothing runs until a terminal operator such as collect is called:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun numbers(): Flow<Int> = flow {
for (i in 1..3) {
delay(100) // pretend we're doing something useful
println("emitting $i")
emit(i)
}
}
fun main() = runBlocking {
println("calling numbers()")
val f = numbers()
println("collecting")
f.collect { value -> println("got $value") }
println("collecting again")
println(f.toList())
}
calling numbers()
collecting
emitting 1
got 1
emitting 2
got 2
emitting 3
got 3
collecting again
emitting 1
emitting 2
emitting 3
[1, 2, 3]
Two things to notice:
numbers()is a regular (non-suspend) function and returns immediately. It only describes the computation.- Flows are cold: every call to
collectruns theflow { }block again from the start. The second collection re-emitted 1, 2, 3.
Other ways to create a flow:
val a = flowOf("red", "green", "blue") // fixed values
val b = listOf(1, 2, 3).asFlow() // from a collection
val c = (1..5).asFlow() // from a range
val d = sequenceOf(1, 2).asFlow() // from a sequence
val e = emptyFlow<String>()
Intermediate operators
Intermediate operators such as map, filter, take and onEach return a new flow. Like the builder, they are lazy, and unlike their collection counterparts, their lambdas can call suspending functions:
suspend fun lookupName(id: Int): String {
delay(50) // e.g. a database call
return "user-$id"
}
fun main() = runBlocking {
(1..10).asFlow()
.filter { it % 2 == 0 }
.map { lookupName(it) }
.take(3)
.collect { println(it) }
}
user-2
user-4
user-6
take(3) cancels the upstream after the third value, so ids 8 and 10 are never looked up.
transform is the most general operator: it can emit any number of values for each input:
val result = flowOf("a", "b")
.transform { value ->
emit(value)
emit(value.uppercase())
}
.toList()
println(result) // [a, A, b, B]
Other useful operators:
fun main() = runBlocking {
val f = flowOf(1, 1, 2, 3, 3, 3, 4)
println(f.distinctUntilChanged().toList()) // [1, 2, 3, 4]
println(f.drop(4).toList()) // [3, 3, 4]
println(f.takeWhile { it < 3 }.toList()) // [1, 1, 2]
println(f.mapNotNull { if (it % 2 == 0) it * 10 else null }.toList()) // [20, 40]
println((1..4).asFlow().runningReduce { a, b -> a + b }.toList()) // [1, 3, 6, 10]
println((1..4).asFlow().scan(0) { acc, v -> acc + v }.toList()) // [0, 1, 3, 6, 10]
println(flowOf("a", "b", "c").withIndex().toList())
// [IndexedValue(index=0, value=a), IndexedValue(index=1, value=b), IndexedValue(index=2, value=c)]
}
Terminal operators
Terminal operators are suspend functions that start collection and produce a result:
fun main() = runBlocking {
val f = (1..5).asFlow()
println(f.toList()) // [1, 2, 3, 4, 5]
println(f.toSet()) // [1, 2, 3, 4, 5]
println(f.first()) // 1
println(f.first { it > 3 }) // 4
println(f.last()) // 5
println(f.count { it % 2 == 1 }) // 3
println(f.reduce { a, b -> a + b }) // 15
println(f.fold("") { acc, v -> acc + v }) // 12345
println(flowOf(42).single()) // 42
println(emptyFlow<Int>().firstOrNull()) // null
}
first() throws NoSuchElementException on an empty flow and single() throws IllegalArgumentException if the flow has more than one element. Use firstOrNull() / singleOrNull() when that is a normal case.
Flows are sequential
By default a single coroutine runs the whole pipeline. Each value travels through all operators to the collector before the next one is produced:
fun main() = runBlocking {
(1..5).asFlow()
.filter {
println("filter $it")
it % 2 == 0
}
.map {
println("map $it")
"string $it"
}
.collect { println("collect $it") }
}
filter 1
filter 2
map 2
collect string 2
filter 3
filter 4
map 4
collect string 4
filter 5
This is the same element-by-element order as a Sequence, and different from a List, where filter would process all elements before map runs. To run stages concurrently, see the Buffering section below.
Changing the context with flowOn
A flow runs in the context of the coroutine that collects it. This property is called context preservation. The code inside flow { } must not switch context itself with withContext:
// WRONG: throws IllegalStateException: Flow invariant is violated
val bad = flow {
withContext(Dispatchers.IO) {
emit(readlnOrNull())
}
}
Instead, use flowOn. It changes the dispatcher for everything upstream of it, while the collector keeps its own context:
fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
fun readRecords(): Flow<Int> = flow {
for (i in 1..3) {
Thread.sleep(50) // blocking work, e.g. reading a file
log("emit $i")
emit(i)
}
}.flowOn(Dispatchers.IO)
fun main() = runBlocking {
readRecords()
.map { it * 10 } // runs in the collector's context (main)
.collect { log("collect $it") }
}
Possible output (worker names and interleaving vary):
[DefaultDispatcher-worker-1] emit 1
[main] collect 10
[DefaultDispatcher-worker-1] emit 2
[main] collect 20
[DefaultDispatcher-worker-1] emit 3
[main] collect 30
flowOn runs the upstream in a separate coroutine and connects the two with a channel, so the producer and the collector now run concurrently.
Buffering
When the producer and the collector are both slow, sequential execution adds their times together. Here emitting takes 100 ms per item and processing takes 300 ms:
import kotlin.system.measureTimeMillis
fun slowNumbers(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
fun main() = runBlocking {
val t1 = measureTimeMillis {
slowNumbers().collect { delay(300); println(it) }
}
println("no buffer: ~${t1 / 100 * 100} ms")
val t2 = measureTimeMillis {
slowNumbers().buffer().collect { delay(300); println(it) }
}
println("buffer: ~${t2 / 100 * 100} ms")
}
1
2
3
no buffer: ~1200 ms
1
2
3
buffer: ~1000 ms
With buffer() the producer runs in its own coroutine and keeps emitting while the collector is busy. Only the first 100 ms of production is on the critical path. buffer(capacity) takes a size; the default is 64.
conflate
If only the latest value matters (a progress bar, a stock price), conflate() drops intermediate values the collector was too slow to process:
slowNumbers()
.conflate()
.collect { delay(300); println(it) }
1
3
While 1 was being processed, 2 and 3 were emitted. 2 was replaced by 3 before the collector asked for the next value.
collectLatest
collectLatest takes a different approach: when a new value arrives, it cancels the collector block still working on the previous one:
slowNumbers().collectLatest { value ->
println("collecting $value")
delay(300)
println("done $value")
}
collecting 1
collecting 2
collecting 3
done 3
This fits cases like search-as-you-type, where the result for an old query is useless once the user types more. There are also mapLatest and transformLatest.
debounce and sample
debounce(timeout) emits a value only after no newer value has arrived for timeout. sample(period) emits the latest value once per period. Both are marked @FlowPreview:
@OptIn(FlowPreview::class)
fun main() = runBlocking {
flow {
emit(1); delay(90)
emit(2); delay(90)
emit(3); delay(1010)
emit(4); delay(1010)
emit(5)
}
.debounce(1000)
.collect { println(it) }
}
3
4
5
The last value is always emitted when the flow completes.
Combining flows
zip pairs up elements from two flows. It completes when either flow completes:
val nums = (1..3).asFlow()
val words = flowOf("one", "two", "three", "four")
nums.zip(words) { n, w -> "$n -> $w" }
.collect { println(it) }
1 -> one
2 -> two
3 -> three
combine emits every time either flow emits, using the latest value of the other one. It is typically used to compute state from several sources:
fun main() = runBlocking {
val nums = (1..3).asFlow().onEach { delay(300) }
val words = flowOf("one", "two", "three").onEach { delay(400) }
combine(nums, words) { n, w -> "$n -> $w" }
.collect { println(it) }
}
1 -> one
2 -> one
2 -> two
3 -> two
3 -> three
combine also accepts more than two flows. merge(f1, f2, ...) interleaves values from several flows of the same type as they arrive, without pairing them.
Flattening flows
When each value starts another asynchronous operation that itself returns a flow, you get a Flow<Flow<T>>. The flatMap* operators flatten it, and differ in how they handle concurrency:
fun request(i: Int): Flow<String> = flow {
emit("$i: first")
delay(500)
emit("$i: second")
}
@OptIn(ExperimentalCoroutinesApi::class)
fun main() = runBlocking {
val ids = (1..3).asFlow().onEach { delay(100) }
println("-- flatMapConcat")
ids.flatMapConcat { request(it) }.collect { println(it) }
println("-- flatMapMerge")
ids.flatMapMerge { request(it) }.collect { println(it) }
println("-- flatMapLatest")
ids.flatMapLatest { request(it) }.collect { println(it) }
}
-- flatMapConcat
1: first
1: second
2: first
2: second
3: first
3: second
-- flatMapMerge
1: first
2: first
3: first
1: second
2: second
3: second
-- flatMapLatest
1: first
2: first
3: first
3: second
flatMapConcatwaits for each inner flow to complete before starting the next.flatMapMergecollects inner flows concurrently (up to 16 at a time by default; passconcurrencyto change it).flatMapLatestcancels the previous inner flow when a new value arrives.
All three (and mapLatest) are marked @ExperimentalCoroutinesApi, hence the @OptIn annotation.
Exceptions
An exception thrown anywhere in the pipeline (producer, operator or collector) propagates out of the terminal operator, so a regular try/catch around collect works:
try {
flowOf(1, 2, 0, 4)
.map { 10 / it }
.collect { println(it) }
} catch (e: ArithmeticException) {
println("caught: ${e.message}")
}
10
5
caught: / by zero
The declarative alternative is the catch operator. It handles exceptions from upstream and can emit a fallback value, rethrow, or log:
import java.io.IOException
fun main() = runBlocking {
flow {
emit(1)
emit(2)
throw IOException("network down")
}
.catch { e ->
println("caught: ${e.message}")
emit(-1)
}
.collect { println(it) }
}
1
2
caught: network down
-1
catch does not see exceptions thrown in the collect { } block, because the collector is downstream of it. To cover the processing code too, move it into onEach and call the no-argument collect():
flowOf("1", "2", "x")
.onEach { println(it.toInt() * 2) }
.catch { e -> println("bad input: $e") }
.collect()
2
4
bad input: java.lang.NumberFormatException: For input string: "x"
catch doesn't intercept the cancellation of the collecting coroutine, so it doesn't break cancellation. See Cancellation and timeouts for why that matters.
onCompletion
onCompletion runs when the flow finishes, whether it completed normally, failed or was cancelled. Its parameter is the exception, or null on success. It doesn't handle the exception, it only observes it:
(1..3).asFlow()
.onStart { println("starting") }
.onCompletion { cause -> println("done, cause = $cause") }
.collect { println(it) }
starting
1
2
3
done, cause = null
Retrying
retry re-collects the upstream when it fails. The predicate decides which exceptions are worth retrying:
import java.io.IOException
fun main() = runBlocking {
var attempts = 0
flow {
attempts++
println("attempt $attempts")
if (attempts < 3) throw IOException("flaky")
emit("ok")
}
.retry(retries = 5) { e -> e is IOException }
.collect { println(it) }
}
attempt 1
attempt 2
attempt 3
ok
retryWhen gives access to the attempt number, which makes exponential backoff easy:
.retryWhen { cause, attempt ->
if (cause is IOException && attempt < 4) {
delay(100L * (1L shl attempt.toInt())) // 100, 200, 400, 800 ms
true
} else {
false
}
}
Cancellation
Collection is a suspending call, so it is cancelled together with the coroutine that runs it. The flow { } builder checks for cancellation on every emit, and operators like take cancel the upstream when they have enough values:
fun main() = runBlocking {
val result = withTimeoutOrNull(250) {
flow {
for (i in 1..10) {
delay(100)
emit(i)
}
}.collect { println(it) }
"finished"
}
println(result)
}
1
2
null
Flows created with asFlow() or flowOf() don't check for cancellation between items, for performance reasons. If such a flow drives a long, busy loop, add .cancellable():
fun main() = runBlocking {
(1..1_000_000).asFlow()
.cancellable()
.collect { value ->
if (value == 3) cancel() // cancels the runBlocking scope
println(value)
}
}
1
2
3
Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was cancelled; job=BlockingCoroutine{Cancelled}@6442b0a6
Without .cancellable() this would print all million numbers before the cancellation is noticed.
launchIn
collect suspends until the flow completes. To collect a flow in the background, for example to react to events, use onEach plus launchIn(scope), which returns a Job you can cancel:
fun main() = runBlocking {
val ticks = flow {
var n = 0
while (true) {
emit(n++)
delay(100)
}
}
val job = ticks
.onEach { println("tick $it") }
.launchIn(this)
delay(350)
job.cancel()
println("stopped")
}
tick 0
tick 1
tick 2
tick 3
stopped
Hot flows: StateFlow and SharedFlow
Everything so far was a cold flow: values are produced per collector, on demand. A hot flow exists independently of collectors and shares the same values with all of them.
StateFlow
StateFlow holds a single current value. New collectors immediately get the current value, then every change. It's the standard way to expose observable state:
class Counter {
private val _count = MutableStateFlow(0)
val count: StateFlow<Int> = _count.asStateFlow() // read-only view
fun increment() = _count.update { it + 1 }
}
fun main() = runBlocking {
val counter = Counter()
val job = launch {
counter.count.collect { println("count = $it") }
}
delay(10)
counter.increment()
delay(10)
counter.increment()
counter.increment()
delay(10)
println("current value: ${counter.count.value}")
job.cancel()
}
count = 0
count = 1
count = 3
current value: 3
StateFlow is conflated: the collector didn't get to run between the second and third increment, so it never saw 2. It also ignores assignments of a value equal to the current one. That's fine for state (you care about the latest value), but wrong for events that must not be lost.
Use update { } rather than _count.value = _count.value + 1: update is an atomic compare-and-set loop, so concurrent increments from multiple threads aren't lost.
Collecting a StateFlow (or any SharedFlow) never completes on its own, so it must be cancelled, as done with job.cancel() above.
SharedFlow
MutableSharedFlow broadcasts values to all current subscribers. It has no initial value, and by default it doesn't replay anything to new subscribers, which makes it a good fit for one-off events:
fun main() = runBlocking {
val events = MutableSharedFlow<String>()
launch { events.collect { println("A got $it") } }
launch { events.collect { println("B got $it") } }
delay(10) // let both subscribers start
events.emit("click")
events.emit("scroll")
delay(10)
coroutineContext.cancelChildren()
}
A got click
B got click
A got scroll
B got scroll
Its behaviour is configured with three parameters:
val events = MutableSharedFlow<String>(
replay = 1, // new subscribers get the last value
extraBufferCapacity = 64, // emit() doesn't suspend while the buffer has room
onBufferOverflow = BufferOverflow.DROP_OLDEST // needs kotlinx.coroutines.channels.BufferOverflow
)
With the defaults (replay = 0, no buffer), emit suspends until every subscriber has received the value, and values emitted while there are no subscribers are simply dropped. tryEmit is a non-suspending variant that returns false when the value can't be buffered.
Converting cold flows to hot: stateIn and shareIn
stateIn and shareIn start a cold flow once in a given scope and share its values among all collectors. This avoids, for example, opening one database query per UI observer:
interface WeatherRepository {
fun temperatureUpdates(): Flow<Double> // cold: each collector polls a server
}
class WeatherViewModel(repo: WeatherRepository, scope: CoroutineScope) {
val temperature: StateFlow<Double?> = repo.temperatureUpdates()
.stateIn(
scope = scope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = null,
)
}
The started policy controls when the upstream is running:
SharingStarted.Eagerlystarts immediately and never stops.SharingStarted.Lazilystarts at the first subscriber and never stops.SharingStarted.WhileSubscribed(stopTimeoutMillis)runs while there are subscribers and stops after the last one has been gone for the given time. The timeout keeps the upstream alive across short gaps, such as an Android configuration change.
shareIn(scope, started, replay) is the same idea but returns a SharedFlow.
Wrapping callback APIs with callbackFlow
Many APIs report values through listeners. callbackFlow turns them into a flow. The awaitClose block runs when the collector stops, which is where you unregister the listener:
import kotlinx.coroutines.channels.awaitClose
import java.util.concurrent.CopyOnWriteArrayList
interface TemperatureSensor {
fun register(listener: (Double) -> Unit)
fun unregister(listener: (Double) -> Unit)
}
fun TemperatureSensor.readings(): Flow<Double> = callbackFlow {
val listener: (Double) -> Unit = { value -> trySend(value) }
register(listener)
awaitClose { unregister(listener) }
}
class FakeSensor : TemperatureSensor {
val listeners = CopyOnWriteArrayList<(Double) -> Unit>()
override fun register(listener: (Double) -> Unit) { listeners += listener }
override fun unregister(listener: (Double) -> Unit) { listeners -= listener }
fun push(value: Double) = listeners.forEach { it(value) }
}
fun main() = runBlocking {
val sensor = FakeSensor()
val job = launch {
sensor.readings().collect { println("temperature: $it") }
}
delay(100) // give the collector time to register its listener
sensor.push(20.5)
sensor.push(21.0)
delay(10)
job.cancelAndJoin()
println("listeners left: ${sensor.listeners.size}")
}
temperature: 20.5
temperature: 21.0
listeners left: 0
Notes:
- Use
trySendfrom callbacks: it doesn't suspend, so it can be called from any thread. It returns a failed result if the buffer (64 by default) is full; add.buffer(...)or.conflate()aftercallbackFlowto change that. awaitCloseis required. Without it the block returns immediately and the flow fails withIllegalStateException.- Call
close()(orclose(exception)) from a callback to end the flow when the source is done.
For a single-value callback, suspendCancellableCoroutine is a better fit than a flow; see Cancellation and timeouts.
Flow vs Sequence vs Channel
Sequence |
Flow |
Channel |
|
|---|---|---|---|
| Lazy / cold | yes | yes (except StateFlow/SharedFlow) |
no, hot |
| Can suspend while producing | no | yes | yes |
| Multiple consumers | each re-runs it | each re-runs it (cold) | each value goes to one consumer |
| Typical use | in-memory pipelines | async streams, observable state | communication between coroutines |
As a rule of thumb, expose Flow from APIs (repositories, services, view models) and keep channels as an implementation detail.
Gotchas
- Flows are cold. Each
collectre-runs the producer. If the producer is expensive (a network request), share it withshareIn/stateIn. - Don't use
withContextinsideflow { }. UseflowOn, which affects only the operators above it. catchonly handles upstream exceptions. Put processing code inonEachbeforecatchif you want it covered.- Collecting a
StateFloworSharedFlownever completes. Collect it in a separate coroutine (launch,launchIn) and cancel it, or usefirst()/take(n). StateFlowis conflated and deduplicated. Don't use it for events that must each be delivered; useSharedFlowor aChannel.asFlow()andflowOf()aren't cancellable between items. Add.cancellable()to tight loops.- Mutable state captured in a flow is shared across collections. Define it inside the
flow { }block if each collector should get its own copy.