Explain it simply
Flows in plain language
A Flow is a recipe for a sequence of values that arrive over time, such as sensor readings, search results or rows from a database. Like a recipe it does nothing on its own: the cooking starts when someone collects the flow, and every collector triggers a fresh run from the beginning.
StateFlow and SharedFlow are the opposite kind of stream, a broadcast that is already running. A StateFlow is a scoreboard: it always shows the latest score, and anyone who looks at it sees the current value at once. A SharedFlow is a radio announcement: only people tuned in at that moment hear it, unless you configure it to replay the last few.
Problem → Why → Solution
The problem: values that arrive over time
Your screen shows live temperature readings. A function that returns List<Int> cannot express values arriving over time: either the screen stays blank until the last reading has been collected, or you switch to callbacks. With callbacks you register a listener, handle three separate methods for values, errors and completion, and you must remember to unregister it, otherwise the sensor keeps a reference to a screen that no longer exists.
Callback code also does not compose. Filtering the readings, converting them to text and switching the work to another thread each need hand-written plumbing inside the listener, and every screen repeats it.
interface Listener {
fun onValue(celsius: Int)
fun onError(error: Throwable)
fun onDone()
}
class Sensor {
fun register(listener: Listener) { /* keep it until unregistered */ }
fun unregister(listener: Listener) { /* forget this call and the screen leaks */ }
}
// Every screen: register, implement three callbacks, filter and convert by hand,
// switch threads by hand, and unregister at exactly the right moment.One value for three channels
A flow packs values, an error signal and completion into one object that composes with operators such as filter and map. It stops by itself when the coroutine collecting it is cancelled, so there is no listener to forget. Because it is built on suspend functions, it can wait between values without blocking a thread.
Core concept: cold flows and hot flows
A cold flow is created with the flow { } builder. The block is a suspending lambda, so it may call delay or any other suspend function, and it hands each value to the collector with emit. Building the flow runs nothing; the block starts only when a terminal operator such as collect, toList, first or reduce is called, and it starts again from the top for every collector. Operators like map, filter, take and onEach are intermediate: each returns a new Flow that merely describes one more step.
By default everything in a flow is sequential. The producer, the operators and the collector run in the same coroutine, one value at a time, and emit suspends until the collector has processed the previous value. That is how flows apply backpressure without extra code: a slow collector simply makes the producer wait. If you want the producer to run ahead, add buffer(), and if the collector should only care about the newest value, add conflate() or use collectLatest.
Errors and threads follow two rules. First, the catch operator handles exceptions thrown upstream of it, that is by the flow builder and the operators above it, but never an exception thrown in the collector's own lambda or by operators below it. Second, a flow runs in the context of whoever collects it, so you change the producer's dispatcher with flowOn, which only affects what is above it. Calling withContext inside flow { } to emit from another dispatcher breaks this rule and throws IllegalStateException: Flow invariant is violated.
Hot flows are different: they exist and hold data whether or not anyone collects. A StateFlow always has a value, so it needs an initial value; its value property can be read at any time; a new collector immediately receives the current value; and it is conflated, so a slow collector may miss intermediate values, and equal values are skipped because StateFlow compares each new value with the old one using equals. A SharedFlow has no initial value, is meant for events, and can replay a configurable number of recent values to newcomers; an event emitted when nobody is subscribed and replay is 0 is simply dropped.
| Type | Starts when | A new collector gets |
|---|---|---|
| Flow | when collected, again for each collector | every value from the beginning |
| StateFlow | already running; always holds a value | the current value, then updates |
| SharedFlow | already running; no initial value | nothing, or the last replay values |
- flow {} describes values over time
- Operators describe what happens to them
- collect runs it, once per collector
- StateFlow keeps the latest value for all
A cold flow is code that has not run yet; a StateFlow is a value that already exists.
General pattern
fun source(): Flow<T> = flow {
// suspending code is allowed here
emit(value)
}
source()
.filter { condition }
.map { transform(it) }
.catch { error -> /* handle an upstream failure */ }
.collect { value -> use(value) } // terminal: this starts the flowBuild the flow with flow { } and emit, describe the pipeline with intermediate operators, and call a terminal operator such as collect to start it. Put catch where you want upstream failures handled and flowOn where the producer should change dispatcher.
Worked example: collecting a cold pipeline twice
readings() prints a line when its body starts, which makes laziness visible. main builds a pipeline with filter and map and prints a message before anything has run. Then it collects the same pipeline twice with toList(): the body starts again for each call, because a cold flow re-executes for every collector.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun readings(): Flow<Int> = flow {
println("flow body starts")
for (celsius in listOf(18, 21, 25, 31)) {
delay(20)
emit(celsius)
}
}
fun main() = runBlocking {
val warm = readings()
.filter { it >= 20 }
.map { "${it}C" }
println("pipeline built, nothing has run yet")
println(warm.toList())
println(warm.toList())
}Code breakdown
- Cold builder
fun readings(): Flow<Int> = flow {flow { } returns a Flow object immediately. The lambda inside is only stored, not run, until someone collects.
- A visible start
println("flow body starts")This line is the proof of coldness: it prints once per collection, not once per flow.
- Emit values
emit(celsius)emit hands one value to the collector and suspends until it is processed. The delay(20) before it shows that a flow can wait between values without blocking a thread.
- Describe the pipeline
.filter { it >= 20 }filter and map return new flows, and nothing runs when they are called. That is why 'pipeline built, nothing has run yet' prints before 'flow body starts'.
- Terminal operator
println(warm.toList())toList() is terminal: it collects the whole flow and returns a List. Calling it twice runs the flow twice; the filter drops 18 and the map adds the C suffix.
pipeline built, nothing has run yet
flow body starts
[21C, 25C, 31C]
flow body starts
[21C, 25C, 31C]- collect() is called
- The flow { } block starts from the top
- emit sends a value through each operator
- The collector's lambda receives it
- The block ends and collect returns
StateFlow: latest value, skipped duplicates, conflation
The code below uses yield() so that the collector gets a turn between writes, which makes the output the same on every run. You can assign MutableStateFlow's value directly, and update { } reads the current value and replaces it as one atomic step.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val state = MutableStateFlow(0)
val seen = mutableListOf<Int>()
val collector = launch { state.collect { seen += it } }
yield()
state.value = 1
state.value = 2
state.value = 3
yield()
state.value = 3
yield()
state.update { it + 1 }
yield()
collector.cancel()
println("collector saw: $seen")
println("current value: ${state.value}")
}The collector first sees 0, the value present when it starts. There is no suspension point between the writes of 1, 2 and 3, so the collector wakes up only for the last one (conflation). Writing 3 again changes nothing because the new value equals the old one. update { it + 1 } produces 4, and the output is collector saw: [0, 3, 4] followed by current value: 4.
SharedFlow: events and replay
Use SharedFlow for events such as a one-time message to the user or a navigation request. With the default (replay = 0) a value emitted while nobody is subscribed is lost; with replay = 1 a newcomer immediately receives the last value.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val events = MutableSharedFlow<String>()
events.emit("early")
val got = mutableListOf<String>()
val listener = launch { events.collect { got += it } }
yield()
events.emit("hello")
events.emit("world")
val late = MutableSharedFlow<String>(replay = 1)
late.emit("kept")
val newcomer = late.first()
listener.cancel()
println("listener got: $got")
println("late subscriber got: $newcomer")
}Nobody was subscribed when 'early' was emitted, so it is lost and the listener receives only hello and world. The second flow has replay = 1, so a subscriber that arrives later through first() gets 'kept'. The output is listener got: [hello, world] and late subscriber got: kept.
Errors, completion and dispatchers
catch handles an upstream error and can let the flow continue with a fresh value, because you may emit inside it. onCompletion runs at the end whether the flow succeeded or failed. flowOn moves only the upstream work and leaves the collector in the context it was collecting in.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val source = flow {
emit(1)
emit(2)
throw IllegalStateException("source broke")
}
source
.catch { e ->
println("caught: ${e.message}")
emit(-1)
}
.onCompletion { println("completed") }
.collect { println("got $it") }
val producerThread = flow { emit(Thread.currentThread().name) }
.flowOn(Dispatchers.Default)
.first()
val onPool = producerThread.startsWith("DefaultDispatcher-worker")
println("producer on shared pool: $onPool")
println("collector still on: ${Thread.currentThread().name}")
try {
flow {
withContext(Dispatchers.Default) { emit(1) }
}.collect { }
} catch (e: IllegalStateException) {
println("invariant: " + e.message?.lineSequence()?.first())
}
try {
flowOf(1, 2, 3)
.catch { println("never reached") }
.collect { value ->
require(value != 2) { "collector failed on $value" }
}
} catch (e: IllegalArgumentException) {
println("escaped catch: ${e.message}")
}
}The first part prints got 1, got 2, caught: source broke, got -1 and completed in that order, so you can see catch stepping in and emitting -1 as a replacement. With flowOn the producer runs on the shared pool while the collector stays on main. The withContext inside the flow gives an IllegalStateException whose message starts with 'Flow invariant is violated:', and in the last part the collector's exception skips catch and escapes as escaped catch: collector failed on 2.
stateIn: turning a cold flow into shared state
stateIn(scope, started, initialValue) collects a cold flow once inside a scope and shares the result with everyone as a StateFlow. Even if five screens watch it, the upstream (for example a database query) runs only once. started decides when that happens: Eagerly at once, Lazily when the first subscriber arrives, and WhileSubscribed(5_000) while there are subscribers plus five seconds after the last one leaves.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val upstream = flow {
emit(10)
delay(30)
emit(20)
}
val state = upstream.stateIn(this, SharingStarted.Eagerly, 0)
println("right after stateIn: ${state.value}")
state.first { it == 20 }
println("after waiting: ${state.value}")
}stateIn hands out the initial value 0 at once and runs the upstream in a separate coroutine of the scope, so the first line is 'right after stateIn: 0'. first { it == 20 } waits until 20 arrives, so the last line is 'after waiting: 20'. In an Android project the usual shape inside a ViewModel is the snippet below; it needs the androidx dependencies, so it is not run here.
class SearchViewModel(repository: SearchRepository) : ViewModel() {
val uiState: StateFlow<UiState> = repository.observeResults()
.map { results -> UiState.Content(results) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UiState.Loading,
)
}In real projects
Where flows show up in real projects
Flows appear wherever values change over time. In most projects the repository exposes a cold Flow, and the UI layer turns it into a StateFlow and observes that.
- Android UI state: a ViewModel owns a MutableStateFlow and exposes it as read-only with asStateFlow(). The screen observes it in a lifecycle-aware way, for example with collectAsStateWithLifecycle, so the upstream can pause while the screen is not visible.
- Databases: libraries such as Room can return query results as Flow<List<T>>, so the UI refreshes by itself every time the table changes.
- One-off events: showing a snackbar or navigating is often modelled with a SharedFlow, but remember that an event can be lost when nobody is subscribed, which is why modelling it as state is often safer.
- Search-as-you-type: operators such as debounce and flatMapLatest group keystrokes and cancel the stale request. Some of these operators need an @OptIn, so check the official docs for their current status.
Common mistakes
Common mistakes with flows
Forgetting the terminal operator
Writing readings().map { ... } without calling collect runs nothing and reports no error. Believing that building a flow starts the work is a classic confusion. End the chain with one of collect, toList, first or launchIn.
Collecting a cold flow twice and expecting one run
Every collect starts the body from the top, so you may make a network request or database query twice by accident. If the result should be shared, use stateIn or shareIn.
Putting catch in the wrong place
catch only handles upstream failures. It does not handle an exception from the collect { } lambda, so wrap the collector in try/catch for that. Place catch below the operators whose failures you want to handle.
Mutating state in place
StateFlow compares a new value with the old one using equals. If you change a MutableList and put the same instance back, it counts as 'equal' and collectors get nothing. In the code below the collector never sees size 2. Use immutable data and assign a new list (or a copy()).
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
val items = mutableListOf("a")
val state = MutableStateFlow<List<String>>(items)
val seen = mutableListOf<Int>()
val job = launch { state.collect { seen += it.size } }
yield()
items.add("b")
state.value = items // same instance, so it is equal and ignored
yield()
state.value = items + "c" // a new list is emitted
yield()
job.cancel()
println("collector saw sizes: $seen")
}Best practices
Best practices
- Expose a MutableStateFlow through asStateFlow() so outside code cannot change the state.
- Represent state as an immutable data class and change it with copy(), so equals detects changes correctly.
- Use flowOn, not withContext inside the flow, to change dispatcher.
- Use StateFlow for things that are state and SharedFlow for one-time events, and design for the fact that an event can be lost.
Mini challenge
Mini challenge: a price alert pipeline
Model a price feed as a flow and write a pipeline that turns the prices above a threshold into alert strings. If the feed contains a negative price, handle the exception with catch and turn it into one error alert. Keep the latest alert in a MutableStateFlow.
- priceFeed(prices) emits each price after delay(10) and throws IllegalArgumentException for a negative price
- alerts(feed, threshold) returns a Flow<String> built with filter, map and catch
- In main, print a normal feed and a feed containing a negative price with toList()
- Store the latest alert in a MutableStateFlow and confirm it with check()
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
// TODO: build the flow with flow { }; for every price, require(price >= 0),
// wait delay(10), then emit it
fun priceFeed(prices: List<Int>): Flow<Int> = TODO()
// TODO: keep prices above threshold, map each to "ALERT <price>",
// and turn an upstream failure into "FEED ERROR: <message>" with catch
fun alerts(feed: Flow<Int>, threshold: Int): Flow<String> = TODO()
fun main() = runBlocking {
// TODO: print alerts for listOf(90, 120, 80, 150) with threshold 100
// TODO: print alerts for listOf(130, -5, 200) with threshold 100
// TODO: collect the alerts of listOf(101, 99, 250) into a MutableStateFlow
// and check() that its value is "ALERT 250"
}Expected: It prints [ALERT 120, ALERT 150], [ALERT 130, FEED ERROR: negative price -5] and last alert: ALERT 250. The 200 after -5 is never reached because the flow ended with the error.
Show hint
In priceFeed call require(price >= 0) { "negative price $price" } before emit. In alerts, putting catch below filter and map lets it receive the upstream error, and emit("FEED ERROR: ...") ends the flow gracefully. For the StateFlow, collect { lastAlert.value = it } is enough.
Show solution
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun priceFeed(prices: List<Int>): Flow<Int> = flow {
for (price in prices) {
require(price >= 0) { "negative price $price" }
delay(10)
emit(price)
}
}
fun alerts(feed: Flow<Int>, threshold: Int): Flow<String> =
feed.filter { it > threshold }
.map { "ALERT $it" }
.catch { emit("FEED ERROR: ${it.message}") }
fun main() = runBlocking {
println(alerts(priceFeed(listOf(90, 120, 80, 150)), 100).toList())
println(alerts(priceFeed(listOf(130, -5, 200)), 100).toList())
val lastAlert = MutableStateFlow("none")
alerts(priceFeed(listOf(101, 99, 250)), 100).collect { lastAlert.value = it }
check(lastAlert.value == "ALERT 250")
println("last alert: ${lastAlert.value}")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A cold Flow runs only when collected and restarts for every collector; operators merely describe the pipeline.
- catch handles only upstream errors and flowOn changes the producer's dispatcher; never use withContext inside a flow.
- StateFlow has an initial value, is conflated and skips equal values; SharedFlow is for events and its replay is configurable.
- stateIn runs a cold flow once and shares it with everyone as a StateFlow.
Kotlin Flows — Kotlin