Snapshot state system

Learn how the Jetpack Compose snapshot system works: MutableState, snapshot isolation, apply observers, derivedStateOf, snapshotFlow and state lists. About 25 minutes.

Why it matters

  • Every mutableStateOf, mutableStateListOf and derivedStateOf in a Compose app sits on the snapshot system. Knowing how reads and writes are tracked explains stale UI, missed updates and extra recompositions.
  • Senior Android interviews ask when derivedStateOf helps, how snapshotFlow turns Compose state into a Kotlin Flow, and why mutating a list inside mutableStateOf does nothing.
  • Snapshot state is thread-safe and can be written from any thread, but only writes to state objects are tracked. Mutating a plain object held inside state is invisible.
  • The same machinery lets Compose run composition in an isolated snapshot and apply all its writes at once, which is why the UI never sees half-applied changes.

The simple explanation

  • Think of the app's state as a shared document with version history.
  • A snapshot is a private copy of the document at one moment. You can read it while others keep editing.
  • A mutable snapshot is a draft: your edits stay private until you apply them, then everyone sees them at once.
  • An apply observer is a subscriber who gets told "these cells changed" every time a draft is applied.
  • derivedStateOf is a formula cell that only tells its readers something changed when its result changes.

What is the snapshot system in Jetpack Compose? It is the state-tracking layer in androidx.compose.runtime that stores every snapshot state object (MutableState, SnapshotStateList, SnapshotStateMap, derived state). It does two jobs: it isolates changes, so code running inside a snapshot sees a consistent view of all state, and it observes reads and writes, so Compose knows which composables to invalidate when state changes.

How a state change reaches the UI.

  1. While a composable runs, Compose records which state objects it reads (a read observer).
  2. Your code writes state.value = x, usually in the global snapshot (the default outside composition).
  3. The global snapshot's changes are applied, and apply observers are told which objects changed. On Android, Compose schedules this for you shortly after a write.
  4. The Recomposer matches the changed objects against recorded reads and invalidates only those restart scopes. They re-run in the next frame.
APIReturnsWhat it does
mutableStateOf(v)MutableState<T>Observable value; a write notifies readers if the new value is not equal (default policy)
mutableStateListOf()SnapshotStateList<T>Observable list; add, remove and set notify readers
derivedStateOf { }State<T>Caches a calculation over other state; readers are notified only when the result changes
snapshotFlow { }Flow<T>Re-runs the block when state it read changes; emits only when the result differs from the previous one
Snapshot.takeSnapshot()SnapshotRead-only view frozen at that moment; read it with enter { }, then dispose()
Snapshot.withMutableSnapshot { }RRuns the block in a mutable snapshot and applies its writes atomically at the end
Snapshot.registerApplyObserver { }ObserverHandleCalled with the set of changed objects each time a snapshot is applied

derivedStateOf is for state that changes more often than the value you need. listState.firstVisibleItemIndex changes on every scrolled row, but "show the scroll-to-top button" only flips at index 0. Wrapping that check in remember { derivedStateOf { ... } } means the composable recomposes twice, not on every row. If the result changes as often as the inputs (filtering a list on every keystroke), derivedStateOf only adds overhead; use remember(key) { ... } or the ViewModel.

snapshotFlow turns Compose state into a cold Flow. Collect it in LaunchedEffect to send scroll positions to analytics or save a draft, and it stops when the composable leaves the composition.

From a write to a redraw
How a state write reaches the UI A composable reads a MutableState during composition; later your code writes it, the global snapshot records and applies the write, apply observers tell the Recomposer which objects changed, and the Recomposer invalidates only the composable that read that state, which re-runs on the next frame. READ WRITE VALUE RECORD WRITE APPLY CHANGES INVALIDATE RE-RUNS Your code onClick Composable restart scope MutableState count Snapshot global Recomposer apply observer
Compose records who read the state. When the write is applied, only those readers are invalidated and re-run on the next frame.

Notes

  • Only writes to snapshot state objects are tracked. state.value.add(x) on a mutableStateOf(mutableListOf()) changes nothing Compose can see; use mutableStateListOf() or assign a new list.
  • mutableStateOf uses structuralEqualityPolicy() by default: writing a value equal to the current one does not invalidate readers. referentialEqualityPolicy() and neverEqualPolicy() exist for special cases.
  • Snapshot state can be written from any thread. On Android, Compose sends apply notifications for global snapshot writes for you, so a write from a background coroutine still reaches the UI.
  • Thread-safe is not the same as race-free: two coroutines doing count.value = count.value + 1 can lose an update. Do read-modify-write in one place, such as a ViewModel holding a MutableStateFlow with update { }.
  • derivedStateOf must be wrapped in remember inside a composable, or a new derived state is created on every recomposition.
  • Inside remember { derivedStateOf { ... } }, only snapshot state is tracked. A plain parameter captured in the block is frozen at the first value; add it as a remember key.
  • snapshotFlow emits only distinct results (like distinctUntilChanged), and it may skip intermediate values if several writes happen before it runs again.
  • Snapshot.takeSnapshot() gives a read-only snapshot; always dispose() it. Writes need a mutable snapshot (takeMutableSnapshot() with apply(), or withMutableSnapshot { }).
  • Composition runs inside a mutable snapshot. Writing state during composition (not in a callback or effect) is a "backwards write" and can cause recomposition loops.
  • You rarely call registerApplyObserver in app code; it is how the runtime (and tools like snapshotFlow) learn about changes.

Code example

A list screen shows a "scroll to top" button only after the first row scrolls away, and reports the first visible row to analytics while the user scrolls.

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
 
@OptIn(FlowPreview::class) // debounce is a FlowPreview API
@Composable
fun ArticleList(
    titles: List<String>,
    onFirstVisibleItem: (Int) -> Unit,
) {
    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()
 
    // Changes on every row; the Boolean flips only twice
    val showScrollToTop by remember {
        derivedStateOf { listState.firstVisibleItemIndex > 0 }
    }
 
    // Keep the latest callback without restarting the effect
    val currentOnFirstVisible by rememberUpdatedState(onFirstVisibleItem)
    LaunchedEffect(listState) {
        snapshotFlow { listState.firstVisibleItemIndex }
            .debounce(500)
            .collect { index -> currentOnFirstVisible(index) }
    }
 
    Box {
        LazyColumn(state = listState) {
            items(titles) { title -> Text(title, Modifier.padding(16.dp)) }
        }
        if (showScrollToTop) {
            FloatingActionButton(
                onClick = { scope.launch { listState.animateScrollToItem(0) } },
                modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp),
            ) { Text("Top") }
        }
    }
}
  • derivedStateOf reads firstVisibleItemIndex many times while scrolling, but ArticleList recomposes only when showScrollToTop changes from false to true or back.
  • snapshotFlow re-runs its block when firstVisibleItemIndex changes and emits only new values. debounce (a FlowPreview API in kotlinx.coroutines) sends the position once scrolling pauses.
  • LaunchedEffect(listState) cancels the collection when ArticleList leaves the composition. rememberUpdatedState makes the effect call the newest onFirstVisibleItem without restarting.

Run the idea in plain Kotlin

A tiny model of derivedStateOf: the derived value is recalculated whenever its input changes, but its reader is only notified when the result changes.

class State<T>(initial: T) {
  private val observers = mutableListOf<() -> Unit>()
  var value: T = initial
      set(v) {
          if (v != field) { // structural equality policy
              field = v
              observers.forEach { it() }
          }
      }
  fun observe(o: () -> Unit) { observers += o }
}

class Derived<T>(private val compute: () -> T, input: State<*>) {
  var computeCount = 0
      private set
  private val readers = mutableListOf<(T) -> Unit>()
  var value: T = compute().also { computeCount++ }
      private set

  init {
      input.observe {
          val next = compute()
          computeCount++
          if (next != value) {
              value = next
              readers.forEach { it(next) }
          }
      }
  }
  fun observe(r: (T) -> Unit) { readers += r }
}

fun main() {
  val firstVisibleIndex = State(0)
  val showScrollToTop = Derived({ firstVisibleIndex.value > 0 }, firstVisibleIndex)

  var recompositions = 0
  showScrollToTop.observe { show ->
      recompositions++
      println("Recompose: showScrollToTop = " + show)
  }

  for (index in listOf(1, 2, 3, 4, 5, 0)) firstVisibleIndex.value = index

  println("Index changed 6 times")
  println("Derived value computed " + showScrollToTop.computeCount + " times")
  println("Reader recomposed " + recompositions + " times")
}

Expected output:

Recompose: showScrollToTop = true
Recompose: showScrollToTop = false
Index changed 6 times
Derived value computed 7 times
Reader recomposed 2 times

In production

Search results stopped updating after a refactor
  • A screen received query: String from its ViewModel as a parameter and computed val results by remember { derivedStateOf { items.filter { it.contains(query) } } }, where items was a SnapshotStateList.
  • Results updated when items were added, but typing a new query did nothing.
  • query is a plain String parameter, not snapshot state. The remember block captured the first value and never re-ran, and derivedStateOf only tracks state reads.
The fix
  • The quick fix made query a key: remember(query) { derivedStateOf { items.filter { it.contains(query) } } }. A new query now creates a new derived state, and item changes are still tracked inside it.
  • Later the filtering moved into the ViewModel, combining the item and query flows and running the filter with an injected Dispatchers.Default.
  • They added a review rule: inside remember { derivedStateOf { } }, every non-state value read in the block must be a remember key.
  • A Compose UI test types two different queries and asserts the visible rows change both times.
Scroll analytics flooded the backend
  • A list sent an analytics event from a LaunchedEffect that collected snapshotFlow { listState.firstVisibleItemIndex }.
  • Every row scrolled past produced an event, so a fast fling sent dozens of events per second.
  • The flow was behaving correctly: it emits each distinct index it sees.
The fix
  • They added .debounce(500) so only the position after scrolling settles is sent.
  • For "user reached the end" they switched to derivedStateOf { lastVisibleIndex >= itemCount - 1 } inside snapshotFlow, so the flow emits only when that Boolean flips.
  • They checked event counts in a debug build with a logging analytics client before shipping.

Common mistakes

  • Mutating an object held inside mutableStateOf. state.value.add(x) or changing a var field of the held object writes nothing to the state, so no reader is invalidated. Use snapshot collections or assign a new immutable value.
  • derivedStateOf without remember. A new derived state is created on every recomposition, so the cache is lost and nothing is saved.
  • Using derivedStateOf when the result changes as often as the input. Filtering a list by a query that changes per keystroke gains nothing from it. Use remember(key) or do the work in the ViewModel.
  • Capturing non-state values in remember { derivedStateOf { } }. Parameters and plain locals are frozen at the first composition. Pass them as remember keys.
  • Writing state during composition. Setting state in the composable body (not in a callback or effect) can trigger another recomposition immediately and loop. Initialise state in remember { mutableStateOf(initial) } or in the ViewModel.
  • Collecting snapshotFlow in a scope that outlives the screen. Collecting it in GlobalScope or an app-wide scope keeps the screen's state objects alive after the user leaves. Collect in LaunchedEffect.
  • Assuming thread safety means no races. Concurrent read-modify-write of a MutableState from several coroutines can lose updates. Keep updates in one owner, such as a ViewModel with MutableStateFlow.update { }.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between mutableStateOf and derivedStateOf, and when is derivedStateOf worth using?”

“How does snapshotFlow work and when would you use it?”

“What is a snapshot in Compose?”

“Can you write Compose state from a background thread?”

Quiz

When does derivedStateOf reduce recompositions?

What does snapshotFlow { listState.firstVisibleItemIndex } emit?

val items = remember { mutableStateOf(mutableListOf<String>()) }, then items.value.add("x"). What happens?

What does Snapshot.takeSnapshot() give you?

0 of 4 answered

Mini task

Add derived state and a snapshotFlow side effect (20 min)

  1. Pick a list screen. Use a LazyColumn with at least 50 rows and hoist its state with rememberLazyListState().
  2. Add a scroll-to-top button. Create val showButton by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } } and show a button only when it is true. The button calls animateScrollToItem(0) from a rememberCoroutineScope().
  3. Count recompositions. Open Layout Inspector with recomposition counts on. Scroll slowly through 20 rows and note the screen's count.
  4. Compare. Temporarily replace the derived state with val showButton = listState.firstVisibleItemIndex > 0 and scroll the same distance. The count should rise far more.
  5. Report the position. Add a LaunchedEffect(listState) that collects snapshotFlow { listState.firstVisibleItemIndex }.debounce(500) and logs the index with Log.d.
  6. Restore the derivedStateOf version.

Done condition: with derivedStateOf, the screen recomposes only when the button appears or disappears, and Logcat shows one index after each scroll pause rather than one per row.

Next: Compose compiler reports