CoursesCompose Multiplatform, one screen from state to pixels
Puzzle 1 · 2 of 4
Which work does a moving card need?
Move the shared card as the user scrolls. Predict which parts of a screen update can be reused.
All puzzles in this course
The problem
The card slides vertically as you scroll. Its content and size stay the same. Which work needs to run in response to the scrolling value?
See it
Scroll sideways to see the full diagram.
The scroll position changes. The text and size stay constant.
Step 1 of 4Compose tracks the phase that reads the position.
Step 2 of 4Placement reads the new offset and moves the existing card.
Step 3 of 4The card appears at its new position. This update can reuse the composition.
Step 4 of 4
The building block
There are three useful rendering phases. Composition decides which UI to describe. Layout measures sizes and places each item. Drawing paints the result. A tracked state read records the phase that actually reads the value.
In this version the observable value is read inside the placement lambda, which is code that runs later when Compose places the card. The position value is already an integer number of pixels:
Box(
modifier = Modifier.offset {
IntOffset(x = 0, y = position.value)
}
) {
Text("Saved item")
}
Now a change in position can update placement without recomposing this box for that change. Related drawing can still run. If you first evaluate the same value up in composition, you have already created a composition dependency by the time the modifier receives it.
Suppose the position only controls a painted color. If the color is read exclusively while drawing, Compose can redraw it without recomposing or relaying out the UI for that change. Choose the phase by the work your value actually drives.
Go deeperMove versus measure
Why might a card changing its height require more work than a card moving vertically?
A different height can require new measurements and can move neighboring items. Moving an item of the same size can reuse its measurement.
Check yourself
What you now know
Where a value is read determines which work that value can invalidate. A read only during placement can move a card without changing its UI description.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.