CoursesCompose Multiplatform, one screen from state to pixels
Puzzle 0 · 1 of 4
Who read the bookmark count?
Tap a bookmark. Work out which part of a shared screen has to run again.
All puzzles in this course
The problem
A reading app has a header that shows the number of bookmarks and a card with a static title. Tapping a bookmark changes the count from 2 to 3. How does Compose know which code needs to run again?
See it
Scroll sideways to see the full diagram.
The shared screen starts with two bookmarks.
Step 1 of 4The header reads the count. The static title uses its own data.
Step 2 of 4The button event changes the count to three. Predict what needs an updated description.
Step 3 of 4The header reads three and describes the updated text.
Step 4 of 4
The building block
A tracked state read is a dependency that Compose records when your code reads an observable value. Here the header reads the bookmark count inside a composable function, a function that describes UI.
@Composable
fun BookmarkCount(count: State<Int>) {
Text("Bookmarks: ${count.value}")
}
The button event changes the observable count held elsewhere. Compose schedules recomposition, running again the parts of the composition that need to update their UI description. The header reads 3 and describes new text. A sibling with a static title has no dependency on this count. Compose can skip unrelated work when it can reuse the result.
That dependency comes from the read. Holding a reference to the state object and reading its value are different operations. If you read the value at the screen's top and hand an integer down, the read happened at the top, even though the header displays it.
Go deeperMove one read
If the header receives a state object and only reads its value inside the header, where is the observable read?
It takes place in the header. Passing the object from the parent does not by itself read the count.
Check yourself
What you now know
A read of observable state gives Compose a dependency to track. When the value changes, Compose can revisit the parts that read it.
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.