In Jetpack Compose, when do you use produceState and when snapshotFlow, and what surprises does each one hold?
answer
- opposite directions across the boundary
- remember plus LaunchedEffect
- awaitDispose for callback sources
- read-only snapshot, equal values dropped
basics
~20 sproduceState turns a non-Compose source into Compose State; snapshotFlow turns Compose state reads into a cold Flow. produceState keeps its last value when a key restarts it; snapshotFlow reads in a read-only snapshot and drops equal values.
solid answer
~50 s`produceState(initialValue, key) { value = ... }` is `remember { mutableStateOf(initialValue) }` plus a `LaunchedEffect(key)` running the producer; it brings a callback, a suspend call or a Flow into the composition as `State`. For callback APIs, register in the producer and end with `awaitDispose { unregister() }`. Its surprises: the State is not reset when a key changes, so the old value shows until the new producer assigns one; equal assignments are conflated. `snapshotFlow { listState.firstVisibleItemIndex }` goes the other way: a cold Flow that runs the block on collection, emits the result, re-runs it when a snapshot state object it read changes, and emits only values unequal to the last. Its block runs in a read-only snapshot, so writing state there fails with `IllegalStateException`, and it models state, so intermediate values may be skipped. You usually collect it inside `LaunchedEffect`.
code
kotlin · 18 lines@Composable
fun rememberHeading(sensorManager: SensorManager): State<Float> =
produceState(initialValue = 0f, sensorManager) {
val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
val rotation = FloatArray(9)
val orientation = FloatArray(3)
val listener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
SensorManager.getRotationMatrixFromVector(rotation, event.values)
SensorManager.getOrientation(rotation, orientation)
value = Math.toDegrees(orientation[0].toDouble()).toFloat()
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
}
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)
awaitDispose { sensorManager.unregisterListener(listener) }
}go deeper
Recall the directions: produceState brings outside data into Compose State, snapshotFlow turns Compose state into a Flow.
Explain produceState as remember plus LaunchedEffect, awaitDispose for callbacks, and snapshotFlow's re-run on changed reads with equality filtering.
Spot stale values after a produceState key change and illegal writes in snapshotFlow, and choose the bridge that matches the direction of data flow.
Decide where bridging belongs: screen-local sources can use produceState, while shared data sources should expose a Flow from outside the UI.
## Two bridges, opposite directions Compose observes **snapshot state** (`mutableStateOf` and friends). Everything else (sensor callbacks, a repository's suspend function, a Flow from a library) is invisible to it. Two APIs cross that boundary: | API | Direction | Returns | Runs in | |---|---|---|---| | `produceState` | Outside source into Compose | `State<T>` | A coroutine owned by the composition | | `snapshotFlow` | Compose state out to Flow code | Cold `Flow<T>` | Wherever you collect it, usually a `LaunchedEffect` | ## produceState: what it is The runtime implementation is two lines: `val result = remember { mutableStateOf(initialValue) }` and `LaunchedEffect(keys) { ProduceStateScopeImpl(result, coroutineContext).producer() }`. So: - the producer **launches** when `produceState` enters composition and is **cancelled** when it leaves; - if a key changes, the running producer is cancelled and **relaunched**; - inside the producer, `this` is a `ProduceStateScope`, which is both a `MutableState` (assign `value`) and a `CoroutineScope` (suspend, launch). For a **callback** source, register the callback and then call `awaitDispose { ... }`. It suspends until the producer is cancelled (left composition, key changed) and always runs its block before resuming, which makes it the place to unregister. ## produceState: the surprises 1. **No reset on key change.** The State is created by `remember` **without** keys, so when the key changes the producer restarts but the State still holds the old value. The screen shows the previous item's data until the new producer assigns. If that is wrong, assign the loading value first thing in the producer: ```kotlin val article by produceState<ArticleUi>(ArticleUi.Loading, articleId) { value = ArticleUi.Loading value = repository.load(articleId) } ``` 2. **Conflation.** With the default structural equality, assigning a value equal to the current one triggers nothing, and observers may see only the latest of several rapid assignments. 3. **A producer that never assigns** leaves the State at `initialValue` forever; Compose's lint checks flag a `produceState` block that does not assign `value`. 4. **Naming.** A composable that returns a value is named like a function (`rememberHeading`, `loadNetworkImage`), starting lowercase. ## snapshotFlow: what it is `snapshotFlow { block }` returns a **cold** Flow. When collected it: 1. runs `block` inside a snapshot, recording every snapshot state object read; 2. emits the result; 3. waits until a newly applied snapshot changes any of those objects, then runs `block` again; 4. emits the new result only if it is **not equal** to the previous one, much like `distinctUntilChanged`. Collection continues until cancelled, so you collect it in a `LaunchedEffect` keyed on the state holder. The effect's lifetime then bounds the collection: ```kotlin val listState = rememberLazyListState() LaunchedEffect(listState) { snapshotFlow { listState.firstVisibleItemIndex > 0 } .collect { scrolled -> onHeaderCollapsed(scrolled) } } ``` Because the block returns a Boolean, the flow emits only when the answer flips, not on every scrolled item. ## snapshotFlow: the surprises - **Read-only snapshot.** The block may not write snapshot state; doing so makes collection fail with `IllegalStateException`. Put writes in the collector. - **State, not events.** The block may run more than once for the same inputs, or once after many rapid changes. Intermediate values can be skipped, so do not count events with it. - **Equality matters.** Emitting a mutable object that changes in place but stays equal emits nothing. - **Threading.** The block runs in the collector's context; inside a `LaunchedEffect` that is the UI thread, so keep the block a cheap read and put heavy work after it. What you do with the resulting Flow (operators, buffering, error handling) is covered in the lesson on Kotlin Flow; collecting a Flow into State for display (`collectAsStateWithLifecycle`) is covered with state and recomposition. ## Picking one - A sensor or a callback API should become UI state: `produceState` with `awaitDispose`. - A one-time suspend load keyed on an id: `produceState(initialValue, id)`, remembering point 1 above. - React in code to scroll position or another Compose state, through Flow operators: `snapshotFlow` inside `LaunchedEffect`.
- In Jetpack Compose, how is produceState built from other effect APIs?It remembers a `mutableStateOf(initialValue)` with no keys and runs the producer in a `LaunchedEffect` keyed on produceState's keys, giving the producer a scope that is both that MutableState and the effect's CoroutineScope. That is why the producer restarts on key changes while the State object, and its last value, survive.
- In Jetpack Compose, why collect a snapshotFlow inside LaunchedEffect rather than in the composable body?Collection suspends indefinitely, and composable functions cannot suspend. `LaunchedEffect` gives it a coroutine whose lifetime matches the call site and cancels it when the composable leaves, which also unregisters the snapshot observer that `snapshotFlow` installed.
- produceState resets to initialValue whenever one of its keys changes
- snapshotFlow emits every intermediate value of the state it reads
- Writing to snapshot state inside snapshotFlow's block is fine
- snapshotFlow starts emitting as soon as it is created, without a collector
- A callback registered in produceState needs a separate DisposableEffect to unregister