# Kotlin Flow: A Mental Model

> Building a correct mental model for Kotlin Flow, from cold-by-default streams to StateFlow and SharedFlow's hot exceptions.

**Date:** 2026-10-25T00:00:00.000Z
**Tags:** Coroutines, Flow

## The intuition

Kotlin Flow is Kotlin's take on reactive programming (A style built around a producer that emits values over time and a consumer that reacts to each one, instead of the consumer pulling a single value once. RxJava, Combine, and the Reactive Streams spec all share this same producer/consumer shape.):
a producer (The side that emits values into a Flow, i.e. whatever's inside the flow \{ } builder block (or calling emit()/trySend() some other way). Not a person or thread, just whichever code produces the values.)
emits values, a consumer collects them. `flow { }` reads like a
description of a producer that's already out there, running, and
`collect { }` just taps into it as the consumer. That's the picture people
carry over from a `List` or an event bus, and it's wrong in a specific way.

* A cold Flow (A Flow built from flow \{ } or a similar builder, with no shared running producer. Each collector gets its own independent run of the builder block.)'s
  builder block *is* the producer, and it isn't a running process, it's a
  recipe. Nothing inside it executes until a consumer collects it.
* Calling `.collect()` runs that recipe from the top, producing values for
  that one consumer alone. A second `.collect()` on the same `Flow` runs
  the producer again, from scratch, independently.
* Two consumers don't split one stream of values between them. Each one
  gets its own producer, run from scratch, as if the `Flow` had never
  been collected before.

That's why a network call or a log line inside a `flow { }` fires once per
collector, not once total, the single most common "wait, why did this run
twice" bug report Flow produces.

* [The Coroutine Tree: What Scope, Job, and Cancellation Actually Mean](/coroutine-tree) — Flow collection always runs inside whatever CoroutineScope called collect(), so cancelling that scope is what stops a cold Flow's recipe (or a shareIn/stateIn producer) mid-run.

## Cold by default: the builder reruns per collector

```kotlin
val userRequests = flow {
    println("Starting network call")
    emit(api.fetchUser())
}

userRequests.collect { println("Collector A got $it") }
userRequests.collect { println("Collector B got $it") }
```

```text
Starting network call
Collector A got User(...)
Starting network call
Collector B got User(...)
```

"Starting network call" prints twice, not once. `userRequests` isn't a
value holding a result, it's a `Flow` object holding a recipe. Each
`.collect()` call is a fresh invocation of that recipe, with its own
`api.fetchUser()` call and its own emission, completely unaware the other
collector exists.

## Same bug, a more realistic shape

The toy example above looks obviously wrong because the `println` gives it
away. The same mechanism causes real duplicate-network-call bugs when the
`Flow` is buried a layer or two down:

```kotlin
// ❌ repository exposes a cold Flow directly
class UserRepository {
    fun observeUser(id: String): Flow<User> = flow {
        emit(api.fetchUser(id)) // runs again for every collector
    }
}

// Two composables, each collecting the same call site's Flow, each
// triggering their own independent api.fetchUser(id) call
@Composable
fun ProfileHeader(repo: UserRepository, id: String) {
    val user by repo.observeUser(id).collectAsState(initial = null)
    // ...
}

@Composable
fun ProfileDetails(repo: UserRepository, id: String) {
    val user by repo.observeUser(id).collectAsState(initial = null)
    // ...
}
```

Nothing here looks like a bug at a glance. `observeUser(id)` reads like
"give me the current user," the same shape as a getter. It's actually "give
me a recipe for fetching the user," and two callers means two recipes run,
two network calls, for what looks like one piece of state.

> **The fundamental**
>
> This is **cold vs. hot stream** semantics. A cold stream's producer does
> no work until a consumer subscribes, and every subscription gets its own
> independent producer, start to finish. A hot stream's producer is already
> running (or already holds a current value) independently of any
> particular consumer, and every consumer taps into that same ongoing
> producer instead of starting a new one.
>
> Kotlin Flow is cold by default. `StateFlow` and `SharedFlow` are the
> deliberate hot exception, covered below.

## Elsewhere: same fundamental, different framework

* **RxJava/RxKotlin**: `Observable.create { }` is cold the same way, each
  `subscribe()` reruns the whole emitter block. `PublishSubject` and
  `BehaviorSubject` are the hot escape hatches, a running pipe that
  subscribers tap into rather than restart.
* **Combine (Swift/SwiftUI)**: a plain `Publisher` is cold, re-executing
  its upstream for every new subscriber unless you insert `.share()` or
  `.multicast()`. `CurrentValueSubject` and `PassthroughSubject` are
  Combine's hot primitives, and `CurrentValueSubject` maps almost exactly
  onto `StateFlow`: both always hold a current value and hand it to every
  new subscriber immediately.
* **JavaScript async generators / `ReadableStream`**: cold by the same
  rule, calling the generator function (or piping the stream) a second
  time reruns it from the start. An `EventTarget`/`EventEmitter` is hot:
  it fires regardless of whether anything is listening, and late
  listeners just miss whatever already happened.
* **Android's old `LiveData`**: hot by construction, there's no
  equivalent of a cold builder block, every observer attaches to the same
  already-alive value holder. This is part of why migrating `LiveData` to
  Flow trips people up: the mental model they'd built for `LiveData`
  assumes hot semantics that a plain `flow { }` doesn't have.

## The hot exception: StateFlow and SharedFlow

`StateFlow` and `SharedFlow` don't rerun a builder per collector, because
there's no builder to rerun. Something calls `MutableStateFlow.value = x`
or `MutableSharedFlow.emit(x)` exactly once, from one place, and every
collector observes that same single stream of updates.

```kotlin
class UserViewModel(private val repo: UserRepository) : ViewModel() {
    private val _uiState = MutableStateFlow<User?>(null)
    val uiState: StateFlow<User?> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            _uiState.value = repo.observeUser(id).first() // runs once, here
        }
    }
}
```

Every screen collecting `uiState` sees the same value, updated at the same
moments, because there's exactly one producer (`viewModelScope.launch`
above) and `uiState` is just a window onto its current value. That's
`StateFlow`'s whole deal: it's conflated (new collectors immediately get
the latest value, not a replay of every past one) and it never completes
on its own.

`SharedFlow` is the more general version: configurable `replay` count
instead of `StateFlow`'s fixed "always exactly the latest value," and no
requirement that it hold a current value at all. `StateFlow` is a
`SharedFlow` with `replay = 1` and an initial value.

### Turning a cold Flow into a hot one on purpose: `stateIn`/`shareIn`

The repository bug from earlier has a real fix, and it's not "don't use
`Flow`," it's "share the one that's cold":

```kotlin
class UserViewModel(repo: UserRepository, id: String) : ViewModel() {
    val user: StateFlow<User?> = repo.observeUser(id)
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = null,
        )
}
```

`stateIn` runs `observeUser(id)`'s cold recipe exactly once, inside
`viewModelScope`, and exposes the result as a `StateFlow` that every
collector shares. `ProfileHeader` and `ProfileDetails` from the earlier
example would now collect the same `user`, with exactly one
`api.fetchUser(id)` call behind both of them.

`SharingStarted.WhileSubscribed(5_000)` is the detail that decides when
the shared producer actually runs: start it once the first collector
shows up, keep it alive 5 seconds past the last collector leaving (so a
quick configuration-change rotation doesn't restart it), then stop and
tear it down if nothing's still listening. `Eagerly` starts it immediately
and never stops; `Lazily` starts on first collector but never stops once
started. Same cold-to-hot conversion either way, just a different answer
to "when does the shared run start and end."

## Common operators at a glance

None of these change the cold-by-default rule above, they're just more
elaborate recipes. Wrapping a cold `Flow` in `combine` or `flatMapLatest`
doesn't make it hot, the combined/mapped `Flow` still reruns its whole
chain per collector unless something shares it with `stateIn`/`shareIn`.

Backpressure (What happens when a producer emits values faster than a collector can process them. A Flow has to decide something: suspend the producer until the collector catches up (the default), buffer the extra values, or drop some of them.)
below is that question specifically: what a `Flow` does when the producer
is faster than the collector, since "wait forever" isn't always the right
answer.

| Operator | Category | What it does |
|---|---|---|
| `map` / `filter` | Transform | Reshapes or drops emissions one at a time, same as `Sequence`/`List` |
| `combine` | Combine multiple flows | Recomputes from the latest value of each source whenever *any* of them emits |
| `zip` | Combine multiple flows | Pairs up the nth emission from each source; waits for every side to emit before producing a pair |
| `merge` | Combine multiple flows | Interleaves emissions from multiple sources into one, in whatever order they arrive |
| `flatMapLatest` | Switch to a new flow | Cancels the previous inner `Flow` and switches to a new one every time the outer `Flow` emits |
| `flatMapConcat` | Switch to a new flow | Runs inner flows one at a time, in order, never overlapping |
| `flatMapMerge` | Switch to a new flow | Runs inner flows concurrently, interleaving their emissions |
| `debounce` | Rate limiting | Drops emissions until a quiet gap passes, then emits only the latest |
| `distinctUntilChanged` | Rate limiting | Drops a new emission if it's equal to the last one actually emitted |
| `buffer` | Backpressure | Runs the producer ahead of a slow collector into a fixed-size buffer, instead of suspending it immediately; `onBufferOverflow` decides what happens once that buffer fills |
| `conflate` | Backpressure | Shorthand for `buffer(capacity = 0, onBufferOverflow = BufferOverflow.DROP_OLDEST)`: no real buffer, just always keep the latest value and drop whatever the collector hasn't gotten to |
| `catch` | Error handling | Catches an upstream exception without cancelling the collector |

`buffer` is the dial `conflate` is one fixed setting of: `buffer(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)` holds one pending
value and drops the one before it once a new value arrives, which is
exactly what `conflate()` does under a shorter name. Pick `buffer`
directly instead when you want a bigger window than one value, or
`BufferOverflow.DROP_LATEST`/`SUSPEND` instead of dropping the oldest.

`combine` is the one that most often hides a cold-rerun bug in practice:

```kotlin
// ❌ combine wraps two cold flows; both still rerun their own recipe
// per collector, so two screens combining the same two repository
// flows means FOUR underlying fetches, not two
val summary = combine(repo.observeUser(id), repo.observeOrders(id)) { user, orders ->
    Summary(user, orders)
}

// ✅ share the combined result once, so every collector taps into
// the same single combine run instead of starting its own
val summary = combine(repo.observeUser(id), repo.observeOrders(id)) { user, orders ->
    Summary(user, orders)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
```

## Common mistakes

### `catch` only sees exceptions thrown *above* it in the chain

```kotlin
flow {
    emit(1)
    throw RuntimeException("boom")
}
.catch { e -> emit(-1) } // ✅ catches the throw above, since catch sits below it
.map { value ->
    if (value == 1) throw RuntimeException("boom downstream")
    value
}
.collect { println(it) }
// Crashes anyway: the second throw happens *after* catch in the chain,
// so catch never sees it. catch is just another cold link in the recipe,
// not a global try/catch around the whole collection.
```

People reach for `catch` expecting it to behave like a surrounding
`try/catch` block, catching anything anywhere in the pipeline. It doesn't.
`catch` is a regular link in the same cold chain as `map`/`filter`, so it
only catches an exception thrown by something upstream of it (closer to
the `flow { }` builder), never something thrown by an operator placed
after it. Put `catch` as the last link before `collect` if you want it to
see everything above.

### Emitting from the wrong `CoroutineContext` crashes with "Flow invariant is violated"

```kotlin
// ❌ withContext inside the builder changes the context emit() runs in,
// which breaks Flow's context-preservation guarantee
flow {
    withContext(Dispatchers.IO) {
        emit(api.fetchUser()) // IllegalStateException at runtime
    }
}

// ✅ flowOn moves the upstream work to IO without emit() ever running
// in a different context than the one flow { } was built in
flow {
    emit(api.fetchUser())
}.flowOn(Dispatchers.IO)
```

A `flow { }` builder guarantees `emit()` always runs in the same
`CoroutineContext` the collector is in, so a collector can trust that
nothing it collects snuck onto a different dispatcher mid-stream. Calling
`withContext` around `emit()` itself breaks that guarantee and throws.
`flowOn` is the correct tool: it moves everything *upstream* of it to the
given dispatcher, while leaving `emit()`'s context-preservation promise
intact for whatever collects it.

### `StateFlow` won't re-emit a value that's structurally equal to the current one

```kotlin
data class UiState(val items: List<Item>)

val _state = MutableStateFlow(UiState(items = mutableListOf()))

// ❌ mutating the same list in place, then reassigning the same
// reference: structurally equal to the old value, so nothing emits
_state.value.items as MutableList
(_state.value.items as MutableList).add(newItem)
_state.value = _state.value // no-op, collectors never see newItem

// ✅ a genuinely new value, so equals() sees a difference and emits
_state.value = _state.value.copy(items = _state.value.items + newItem)
```

`StateFlow` is conflated: assigning `.value` only emits to collectors if
the new value isn't `equals()` to the current one. Mutating a held
collection in place and reassigning the same reference looks like an
update but isn't one as far as `StateFlow` can tell, since nothing about
the reference actually changed. This is the same reason immutable data
classes and `copy()` are the convention around `StateFlow`, not a style
preference.

### Forgetting `awaitClose` crashes `callbackFlow` immediately

`callbackFlow` (A Flow builder for wrapping callback-based APIs (listeners, OS callbacks) that don't fit flow \{ }'s plain suspend-and-emit shape. You register the callback inside the block, forward each invocation into the Flow with trySend(), and unregister it in awaitClose when the collector goes away.)
exists for exactly the APIs a plain `flow { }` can't express: something
that hands you values through a callback/listener instead of letting you
`emit()` directly, like a location provider or a `View`'s click listener.
It's still a cold `Flow` underneath, built the same `flow { }`-shaped way,
just with a registered callback standing in for the emissions.

```kotlin
// ❌ the block returns right after registering the callback, with
// no suspension point: callbackFlow treats that as a bug and throws
fun locationUpdates(client: LocationClient): Flow<Location> = callbackFlow {
    val callback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult) {
            trySend(result.lastLocation)
        }
    }
    client.requestLocationUpdates(callback)
    // IllegalStateException: callbackFlow block completed, but the
    // channel was never closed, so there's no deterministic moment
    // left to unregister the callback above
}

// ✅ awaitClose suspends until the collector cancels (or the channel
// is closed some other way), which is also the only safe place to
// unregister the callback
fun locationUpdates(client: LocationClient): Flow<Location> = callbackFlow {
    val callback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult) {
            trySend(result.lastLocation)
        }
    }
    client.requestLocationUpdates(callback)
    awaitClose { client.removeLocationUpdates(callback) }
}
```

`callbackFlow`'s whole contract is built around having one deterministic
moment to clean up whatever callback it registered. If the block can
return on its own, there's no such moment, the callback would just leak,
registered forever with nothing left able to unregister it. So
`callbackFlow` enforces the contract at runtime: the block must end in a
suspension point, almost always `awaitClose { }`, or it throws instead of
silently leaking.

### `callbackFlow` is cold too, which means the callback re-registers per collector

```kotlin
fun locationUpdates(client: LocationClient): Flow<Location> = callbackFlow {
    val callback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult) {
            trySend(result.lastLocation)
        }
    }
    client.requestLocationUpdates(callback) // registered again per collector
    awaitClose { client.removeLocationUpdates(callback) }
}
```

Wrapping a callback in `callbackFlow` doesn't opt it out of cold-by-default,
it's still built from the same `flow { }`-shaped recipe. Two collectors
register two separate location listeners with the OS, each torn down
independently on its own collector's cancellation. The fix is the same one
above: `shareIn` it once in a scope that outlives any single collector,
instead of letting every screen that wants location data call
`locationUpdates()` itself.

### `Flow` has no `.value`, `StateFlow` does, and reaching for one when you meant the other is a type error waiting to happen

A plain `Flow<T>` can't be read synchronously, there's no current value to
read since nothing's running until you collect it. `StateFlow<T>` always
has one. Code that generically takes a `Flow<T>` parameter but actually
needs `.value` is a sign the function quietly assumed hot semantics it
was never guaranteed.

**A `Flow` is a recipe, not a pipe already carrying values: cold by
default, every `collect()` reruns its own independent copy, and
`StateFlow`/`SharedFlow` (or `stateIn`/`shareIn` on top of a cold `Flow`)
are the deliberate opt-in to run it once and let everyone share the
result.**


---

Canonical page: https://recomposed.blog/kotlin-flow-mental-model