Jetpack Compose Mechanisms, Part 2: How the Runtime Remembers and How the UI Becomes Pixels
Jetpack Compose Mechanisms, Part 2: How the Runtime Remembers and How the UI Becomes Pixels
In Part 1, the compiler turned a plain function into one that can skip itself and run again on its own. That rewrite explains how a composable restarts, but not when it restarts, and not where the values it needs between runs actually live. You rely on the answers every day: you wrap a value in
remember, reach for mutableStateOf, and the screen updates. But when remember alone never updates the screen, or mutableStateOf without remember keeps resetting, the explanation has to come from the runtime. And once the runtime knows what changed, Compose UI still has to turn that record into something Android can draw.
In this article, you'll dive deep into the Compose runtime and the UI layer, starting from four ways of holding a value and working toward pixels: the SlotTable and its gap buffer, positional memoization, state reads as subscriptions, frame aligned recomposition, the Applier, the Layout primitive, and AndroidComposeView.
This is the second article of a three part series based on my DroidKaigi 2026 & Droidcon Berlin 2026 talk, Jetpack Compose Mechanisms. You can follow along with the slides, and the diagrams in this series come from them. Part 1 covered the compiler, and Part 3 applies the whole picture to performance work. The source excerpts in this article come from the Compose 1.13.0-beta01 sources.
Two triggers: Input changes and state reads
Part 1 ended with a function that decides, every time it is called, whether its body needs to run. That covers one of the two ways a composable runs again:
- Input changes: when its caller runs again, the generated code compares each argument with the value stored on the previous run, and runs the body if any of them differs. This is the
$composer.changed(name)check from Part 1. - State reads: a composable that reads a
Stateis recorded as depending on it. When that state changes, the runtime schedules the nearest restartable scope that did the read to run again, even if its caller never runs.
Either one is enough to run the body again. The first needs nothing from you beyond passing arguments. The second is the one you set up with mutableStateOf, almost always wrapped in remember, and that pairing is where most of the confusion starts.
The fundamental problem: Four ways to hold a value
Here are four alternative versions of the same composable. Each one holds a Dove, and they differ only in whether they use remember, mutableStateOf, or both:
@Composable
fun BirdProfile() {
var bird = Dove()
}
@Composable
fun BirdProfile() {
var bird = remember { Dove() }
}
@Composable
fun BirdProfile() {
var bird = mutableStateOf(Dove())
}
@Composable
fun BirdProfile() {
var bird = remember { mutableStateOf(Dove()) }
}
You probably know that remember and mutableStateOf belong together. The question is what each one contributes on its own, and the answer splits along the two halves of the runtime: one half keeps values between runs, the other reports changes.
Without remember: A new value on every run
Start with the plain version. A composable can run many times, and every run executes the body from the top, so a plain Dove() call creates a new instance every time:

Two recompositions mean three runs and three different Dove instances. Nothing connects one run's bird to the next run's, because the local variable lives exactly as long as one execution of the function.
remember: Storing the value in the SlotTable
Wrap the call in remember, and every run gets the same instance back:

The value has to live somewhere between runs. The composition keeps everything it records in a structure called the SlotTable: the groups from Part 1, and the values recorded inside them, each in a slot. remember writes its value into a slot and reads it back on the next run. A local value you create without remember is never written there, so the next run has nothing to read back. Arguments are a different matter: as Part 1 showed, changed() keeps each argument it compares in a slot, which is why the diagrams below contain values like "Count: 0".
Looking at the implementation of remember:
@Composable
public inline fun <T> remember(crossinline calculation: @DisallowComposableCalls () -> T): T =
currentComposer.cache(false, calculation)
It delegates to Composer.cache:
public inline fun <T> Composer.cache(invalid: Boolean, block: @DisallowComposableCalls () -> T): T {
@Suppress("UNCHECKED_CAST")
return rememberedValue().let {
if (invalid || it === Composer.Empty) {
val value = block()
updateRememberedValue(value)
value
} else it
} as T
}
Notice the structure:
- Read:
rememberedValue()returns the value stored at this same point in the composition on the previous run, orComposer.Emptyif nothing has been stored yet or the content is being reused. - Compute once: on the first composition, or when
invalidistrue, the lambda runs andupdateRememberedValuestores its result. - Reuse: on every later run, the stored value comes back and the lambda does not run at all.
remember with keys only changes the invalid flag. remember(key1) { ... } calls cache(currentComposer.changed(key1), calculation), the same changed you saw in Part 1, so the value is recomputed only when the key no longer equals the one stored last time. In compiled code, the compiler inlines this logic and compares keys itself. A key that is a stable parameter can reuse the $dirty bits from Part 1, and a constant key is never compared or stored at all. A parameter known to be unstable always gets its own changed() call, while one whose stability is only decided at runtime, such as a List since Kotlin 2.4, gets that call only when the caller marks the argument as unstable. Part 3 uses keyed remember to stop a list from being rebuilt.
Inside the SlotTable: Groups, slots, and a gap buffer
To see how the table is laid out, follow a small counter through two compositions:
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
if (count > 0) {
Icon(Icons.Default.Star, contentDescription = null)
}
Text("Count: $count")
}
The composer walks the SlotTable in the same order as the code runs, like a cursor moving through a document. The diagrams below flatten the table into a single column to keep the picture readable; the real table keeps groups and slots in two separate arrays. They also write the state's current value into the code, so mutableStateOf(1) in a later diagram means the state now holds 1, not that the source changed.
On the first composition, the recompose scope, the remembered state, and the Text call are recorded in order. count is 0, so the if block does not run, and apart from an empty group that marks the branch, nothing is recorded for Icon. The empty entries after them are the gap.
![]()
Now count changes to 1, and recomposition walks the same code again. This time the if block runs, and Icon needs room in the middle of the table, between the state and the Text call.
This is where the gap buffer comes in. A gap buffer is the data structure many text editors use for the document you type into: the text lives in one array with a block of empty space, the gap, kept at the cursor. Typing fills the gap without moving anything else, and moving the cursor moves the gap. The SlotTable works the same way, with one detail the diagrams compress. While your code runs, the composer only reads the existing table. It composes new content such as Icon into a separate insert table, and it records the edits it needs in a change list. When those changes are applied, a writer moves the gap to the insertion point. That move copies the entries in between, here the two entries of the Text call, to the other side of the gap, and Icon's entries are then written into the empty space.

Icon fills the gap, and Text's stored argument changes to "Count: 1". The diagram shows the table while the writer is still open; when it closes, the gap moves back to the end:

If you examine SlotWriter, the class that edits the table, you'll find a gap tracked for each of the two arrays. Each group occupies five Ints in the groups array, which is why the group gap is computed by dividing by Group_Fields_Size:
private var groupGapStart: Int = table.groupsSize
private var groupGapLen: Int = groups.size / Group_Fields_Size - table.groupsSize
private var slotsGapStart: Int = table.slotsSize
private var slotsGapLen: Int = slots.size - table.slotsSize
Each gap is just a start index and a length, and moveGroupGapTo and moveSlotGapTo slide it to wherever the next edit happens. Moving a gap copies the entries it passes over, so the cost grows with how far it travels. A removal moves the gap to the removed entries and widens it over them instead of copying them. The writer's cursor only moves forward, so insertions and removals at the cursor carry the gap forward after its first move. Moving a group is the exception: reordered keyed content is applied by inserting the group at the cursor and removing it from its old position further ahead, which leaves the gap there, and the next edit pulls it back. When the writer closes, it moves the gap back to the end of the table so that readers never have to step over it.
The gap buffer is the default SlotTable implementation. An experimental replacement, a linked structure designed to reduce the amount of internal array copying when content is deleted, moved, or reordered, sits behind ComposeRuntimeFlags.isLinkBufferComposerEnabled and is off by default. The New LinkBuffer SlotTable: What Changes and Why It Matters covers what changes when you turn it on.
Positional memoization: The call position is the identity
The table mirrors the structure and the order of your composable calls, which gives the runtime a way to identify values without names: a value belongs to the position where it was recorded. During recomposition, the composer walks the code again, and when it reaches the same call at the same position, it finds the slot recorded there and reuses the value instead of creating a new one. The runtime recognizes the same call by its group key, the integer the compiler generated in Part 1, and the same position by the order in which the groups appear. This is called positional memoization.
Two consequences show up in everyday code. First, each call site has its own state: call the same composable twice, and each call gets its own remember slots, because each call has its own position. Second, content that moves around, such as items in a list that can be reordered, needs key() to carry its identity with it. How Compose Remembers: The Positional Memoization Behind remember and State follows this mechanism through
cache and the slot cursor in detail.
remember without State: A value that tells no one
So remember gives you values that survive recomposition. That is not the same as a screen that updates. Consider a counter that keeps its count in a remembered object:
class CountHolder {
var value = 0
}
@Composable
fun Counter() {
val holder = remember { CountHolder() }
Text("Count: ${holder.value}")
Button(onClick = { holder.value++ }) { Text("Add") }
}
Click the button three times, and holder.value becomes 3: the holder is remembered, so every click increments the same object. The text still says "Count: 0". Nothing told the runtime that anything changed, so nothing ran again. The new value only appears when something else happens to recompose Counter, and then the text jumps straight to "Count: 3".
A shorter version of this example looks like it should behave the same way:
var count = remember { 0 }
Text("Count: $count")
Button(onClick = { count++ }) { Text("Add") }
The talk's slides show this version keeping its count across a recomposition. It does not: even after a recomposition, it reads "Count: 0". remember stored the Int value 0, not the variable. The click increments a local copy captured by the lambda, nothing writes the new number back into the slot, and the next run reads 0 again. To keep a value with remember, the remembered object itself has to hold it.
State: Reading is the subscription
The missing piece is a way to tell the runtime that something changed, and that is what State is for. Like LiveData or StateFlow, it holds an observable value. Unlike them, it has no subscription call. With LiveData you call observe, and with StateFlow you call collect. With State you call nothing: when a composable reads state.value, Compose records the read, and when the value changes, it schedules recomposition for the composables that read it. Reading the value is the subscription.

mutableStateOf does not hand you a plain box. It returns state backed by Compose's snapshot system, the layer underneath Compose state that gives the runtime a consistent view of every state object and lets it observe reads and writes. The value lives in a chain of state records that starts at next, which lets each snapshot see its own version of the value. Looking at SnapshotMutableStateImpl, the class behind mutableStateOf:
override var value: T
get() = next.readable(this).value
set(value) =
next.withCurrent(this) {
if (!policy.equivalent(it.value, value)) {
next.overwritable(this, it) { this.value = value }
}
}
With by, every read of count goes through this getter. It looks like a plain getter, but readable is where the read leaves a trace. Trimmed to its first lines:
public fun <T : StateRecord> T.readable(state: StateObject): T {
val snapshot = Snapshot.current
snapshot.readObserver?.invoke(state)
// ...
}
Every read calls the current snapshot's read observer. While a composition is running, that observer belongs to the composition, and it records the read against the scope that is currently executing. Looking at CompositionImpl.recordReadOf, trimmed to the path that matters:
composer.currentRecomposeScope?.let { scope ->
scope.used = true
val alreadyRead = scope.recordRead(value)
if (!alreadyRead) {
if (value is StateObjectImpl) {
value.recordReadIn(ReaderKind.Composition)
}
observations.add(value, scope)
}
}
observations maps each state object to the scopes that read it. The read creates the dependency, and the dependency points at the scope that did the reading. recordReadIn marks the state itself as read during composition, a flag the Recomposer uses later to ignore writes to states that no composition ever read. scope.used = true is also the flag Part 1's endRestartGroup checks: a scope that read a state is the kind of scope that gets a restart lambda. The Snapshot System: How Compose Tracks and Batches State Changes covers the records and snapshots behind
readable and overwritable.
State writes: Record now, recompose on the next frame
Now the write side. The setter compares the new value with the current one through the state's policy, structuralEqualityPolicy() by default, so writing an equal value does nothing at all. A different value is written to a record owned by the current snapshot (the first write in a snapshot creates it, and later writes in the same snapshot overwrite it), and the write is reported to the snapshot's write observers. The setter does not recompose anything.

Recomposition happens later. On Android, GlobalSnapshotManager registers a global write observer that schedules a notification on the main thread:
val channel = Channel<Unit>(1)
CoroutineScope(AndroidUiDispatcher.Main).launch {
channel.consumeEach {
sent.set(false)
Snapshot.sendApplyNotifications()
}
}
Snapshot.registerGlobalWriteObserver {
if (sent.compareAndSet(false, true)) {
channel.trySend(Unit)
}
}
From a write to a recomposition, four steps happen:
- Accumulate: each write lands in the global snapshot's set of modified state objects.
- Schedule: the first write in a burst requests a flush on the main thread, and
sentmakes the writes that follow it reuse that pending request. - Invalidate: on the main thread,
sendApplyNotifications()reports every modified state at once. TheRecomposerskips states that were never read during composition, and invalidates the scopes recorded inobservationsfor the rest. - Recompose: the
Recomposerwaits for the next frame before recomposing those scopes, and the comment in its loop says why: "Align work with the next frame to coalesce changes."
So three writes do not necessarily mean three recompositions. Writes made in several separate tasks before the next frame still cost one recomposition. Writes made by frame callbacks at the start of a frame, such as animation updates, are recomposed within that same frame, while a write made later in the frame, during layout or drawing, waits for the next one. I ran this in a Robolectric test on the JVM (Kotlin 2.3.21, Compose 1.11.2), where the test harness flushes the notifications and drives the frames itself: writing a state three times in one main thread task recomposed its reader once and displayed the last value, while three writes in three separate frames recomposed it three times. And because a write only reaches the scopes that recorded a read, the place where you read a state defines what recomposes.
This also explains why mutableStateOf without remember keeps resetting. Without remember, the body calls mutableStateOf again on every run. A click writes 1, the write invalidates the scope that read the state, and the recomposition it triggers creates a fresh state holding 0 and reads that one instead. The state did report its change; the next run threw it away.
The cases answered: What each piece contributes
Back to the four versions of BirdProfile. Running each one in the same setup, forcing two recompositions, and comparing the instances each run saw gives this:
| Version | Kept across runs | Reports changes | Distinct Dove instances over 3 runs (measured) |
|---|---|---|---|
Dove() | No | No | 3 |
remember { Dove() } | Yes | No | 1 |
mutableStateOf(Dove()) | No | Yes, but a new state replaces it on every run | 3 |
remember { mutableStateOf(Dove()) } | Yes | Yes | 1 |
The counter versions make the same split visible on screen. After three clicks:
var count = 0: "Count: 0", before and after a recomposition.var count = remember { 0 }: "Count: 0", before and after a recomposition, while the click lambda counted 1, 2, 3 on its local copy.remember { CountHolder\(\) }: "Count: 0" after the clicks, and "Count: 3" after an unrelated recomposition.var count by mutableStateOf\(0\): "Count: 0", even though each click recomposedCounter.var count by remember { mutableStateOf\(0\) }: "Count: 3".
Only the last version does what you want:
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Text("Count: $count")
Button(onClick = { count++ }) { Text("Add") }
}
remember keeps the same state object across runs, and the state reports every change to the scopes that read it.
From a flat table to a tree: LayoutNode
So far, everything has lived inside the runtime. The next question is how the composition becomes something you can see.
The SlotTable diagrams already contained a hint: next to the remembered state and the stored arguments, the table holds LayoutNode entries. LayoutNode is the core of Compose UI. Column, Row, Text, and Image all contribute nodes to the same hierarchy. Measurement and placement happen on that tree, while drawing, input, focus, and accessibility attach to nodes through modifiers. A Button in Compose is not backed by an android.view.View; underneath it there is a node hierarchy that Compose owns.
The SlotTable and the tree are two different things. The table is an ordered record of what was called and with which values: its groups form a tree, but they are stored flat, each group followed immediately by its children. The LayoutNode tree is what gets measured and drawn, and its parent and child links live in the nodes themselves. Something has to turn changes in the first into changes in the second.
The Applier: The runtime never inspects the tree
That something is the Applier. If you examine its interface in the runtime:
public interface Applier<N> {
public val current: N
public fun down(node: N)
public fun up()
public fun insertTopDown(index: Int, instance: N)
public fun insertBottomUp(index: Int, instance: N)
public fun remove(index: Int, count: Int)
public fun move(from: Int, to: Int, count: Int)
public fun clear()
public fun apply(block: N.(Any?) -> Unit, value: Any?) { /* ... */ }
public fun reuse() { /* ... */ }
// ...
}
Move down and up, insert, remove, move, plus apply, which delivers property updates to the current node: that is very nearly the whole interface. It is generic over the node type N, and nothing in it mentions views, canvases, or pixels. During composition, the runtime records the changes it needs in a change list, and when the composition is applied, those changes are carried out through the applier. The runtime does hold the nodes, since it creates each one through a factory it is handed and keeps it in a slot, but it never looks inside them. The one thing it asks of a node is whether it implements ComposeNodeLifecycleCallback, so that it can tell the node when it is reused, deactivated, or released. That separation is why the same runtime drives trees that have nothing to do with LayoutNode: vector graphics written with the Group and Path composables build a tree of VNodes through VectorApplier, Glance builds app widgets, Compose HTML builds DOM nodes, and Mosaic builds terminal UIs.

Compose UI decides what the tree is made of by supplying the applier. UiApplier is an AbstractApplier<LayoutNode>:
internal class UiApplier(root: LayoutNode) : AbstractApplier<LayoutNode>(root) {
override fun insertTopDown(index: Int, instance: LayoutNode) {
// Ignored. Insert is performed in [insertBottomUp] to build the tree bottom-up to avoid
// duplicate notification when the child nodes enter the tree.
}
override fun insertBottomUp(index: Int, instance: LayoutNode) {
current.insertAt(index, instance)
}
override fun remove(index: Int, count: Int) {
current.removeAt(index, count)
}
// ...
}
Each operation becomes a call on a LayoutNode. insertTopDown is ignored on purpose: Compose UI builds the tree bottom up, attaching children before their parent joins the tree, so nodes are not announced twice as they enter it. LayoutNode enters the picture through UiApplier, and through the node factories that UI components hand to the runtime, which is the next piece.
The Layout primitive: Where most components end
Text, Image, Icon, Row, Column, and Box look very different from the outside, but almost all of them end in the same call: the Layout composable. Layout is what emits a node into the composition. Looking at the overload that leaf components use:
@Composable
@UiComposable
public inline fun Layout(modifier: Modifier = Modifier, measurePolicy: MeasurePolicy) {
val compositeKeyHash = currentCompositeKeyHashCode.hashCode()
val materialized = currentComposer.materialize(modifier)
val localMap = currentComposer.currentCompositionLocalMap
ReusableComposeNode<ComposeUiNode, Applier<Any>>(
factory = ComposeUiNode.Constructor,
update = {
set(measurePolicy, SetMeasurePolicy)
set(localMap, SetResolvedCompositionLocals)
reconcile(ApplyOnDeactivatedNodeAssertion)
set(materialized, SetModifier)
set(compositeKeyHash, SetCompositeKeyHash)
},
)
}
ReusableComposeNode asks the runtime to create a node with factory, which builds a LayoutNode, and to keep it up to date with the values set in update. What makes one component different from another comes down to two of those values: the measurePolicy, which decides how the node measures, and the modifier, which attaches drawing, input, and accessibility. The rest of update is the same plumbing for every component.
The everyday components all go through Layout. A few places create LayoutNodes directly instead: SubcomposeLayout, which lazy lists are built on, and AndroidView. This is also why a custom layout is not a second class citizen: call Layout with your own MeasurePolicy, and you get the same kind of node that Row and Column produce.
Text: A layout that measures nothing
Text shows how far a component travels before it reaches Layout:

The Material 3 Text merges its styling and calls BasicText from foundation, and BasicText chooses a modifier and ends in a single Layout call:
val finalModifier =
if (selectionController != null || onTextLayout != null || autoSize != null) {
modifier.textModifier(/* ... */)
} else {
modifier then TextStringSimpleElement(text = text, style = style, /* ... */)
}
Layout(finalModifier, EmptyMeasurePolicy)
On the common path, with no selection, no onTextLayout callback, and no auto sizing, the modifier is TextStringSimpleElement. Now look at the measure policy:
private object EmptyMeasurePolicy : MeasurePolicy {
private val placementBlock: Placeable.PlacementScope.() -> Unit = {}
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints,
): MeasureResult {
return layout(constraints.maxWidth, constraints.maxHeight, placementBlock = placementBlock)
}
}
It measures nothing. It has no children to measure, and it simply takes the largest size its constraints allow. That does not mean the text is never measured; the work moves into the modifier. TextStringSimpleElement creates a TextStringSimpleNode, which is a LayoutModifierNode, a DrawModifierNode, and a SemanticsModifierNode at once. A layout modifier sits in front of the node's own measure policy: it receives the constraints first and decides what to pass on. TextStringSimpleNode measures the string, then passes constraints fixed to the text's size, so when EmptyMeasurePolicy takes the largest size allowed, that size is the text's.
The same node draws the glyphs and describes the text to accessibility services. Text is a LayoutNode like any other, and everything that makes it text lives in its modifier node. It also shows that Modifier.Node is a first class extension point for custom measuring and drawing: Text itself is built on one.
AndroidComposeView: Where the tree meets Android's Canvas
The last step is getting the tree onto the screen. On Android, setContent installs a ComposeView, which adds an AndroidComposeView, a ViewGroup that owns the root LayoutNode.

When the composition is created, the applier is bound to that root:
Composition(UiApplier(composeView.root), composeViewContext.compositionContext)
From then on, every change the runtime applies lands under composeView.root. When Android asks the view to draw, dispatchDraw does the rest. Trimmed to its core:
override fun dispatchDraw(canvas: android.graphics.Canvas) {
measureAndLayout()
canvasHolder.drawInto(canvas) {
root.draw(canvas = this, graphicsLayer = null)
}
}
It measures and lays out whatever is still pending in the LayoutNode tree, then draws the root onto the Android Canvas it was handed, and each node draws through its modifier chain. Changes that can resize the view itself go through Android's regular onMeasure and onLayout instead. Android does not know it is drawing Compose UI. To the platform, AndroidComposeView is an ordinary view drawing itself, and from here the usual rendering path takes over: with hardware acceleration, the drawing is recorded into display lists that the render thread turns into pixels.

The same boundary makes interop work in both directions: ComposeView puts this view inside an XML layout, and AndroidView puts an ordinary View back inside the LayoutNode tree.
Conclusion
In practice, this gives you two questions to ask of any value in a composable. Does it need to survive recomposition? That is the job of remember. Does a change to it need to reach the screen? That is the job of State. Most UI state needs both, and a value that needs neither is just a local. Then look at where the state is read, because the scope that reads it is the scope that runs again when it changes. On the UI side, when a component sizes or draws in a way you did not expect, read its measure policy and its modifier chain, because that is all Compose UI sees of it.
The runtime never draws and never looks inside a node. Compose UI supplies everything specific to the screen: the node type, the applier, the frame clock, and the scheduling. The two meet through an interface small enough to read in one sitting. That boundary is also where performance work pays off: a recomposition the runtime skips leaves the applier nothing to carry out, and Part 3 is about skipping it on purpose.
If you want to go deeper than this series can, my book Jetpack Compose Mechanisms walks through the compiler, the runtime, and Compose UI in much more detail, reading each one from the actual source the same way this series does.
As always, happy coding!
— Jaewoong (skydoves)

