CoursesCompose Multiplatform, one screen from state to pixels
Puzzle 2 · 3 of 11
Which row is which?
Puzzle 1's next run matches each call to its group by key and order. A loop calls the same composable from one line, once per item. Here's what happens to a row's remembered values when an item is inserted at the top, and how a key keeps them with the right item.
All puzzles in this course
The problem
Puzzle 1 showed the next run matching each call to its group: by the call's key, and, for calls with the same key, by their order. An if keeps a group of its own, so nothing after it shifts. A list is different. A loop calls PersonRow once per person, always from the same line of code, so every row carries the same key and only order tells them apart. You type a note into Ben's row, kept with remember, and then a new person arrives at the top of the list. Whose row shows your note now?
See it
Scroll sideways to see the full diagram.
One loop, one call site: every
PersonRowcall opens a group with the same key, 55 here. You typed a note into Ben's row; it sits in a slot of the second group.Step 1 of 5Zoe is inserted at the top of the list, and the loop runs again. Predict: whose row shows the note now?
Step 2 of 5Ana's. The keys are all equal, so groups go out by order: Zoe takes the first group, Ana the second, with Ben's note. Cleo gets a new group at the end.
Step 3 of 5Now each row is wrapped in
key()with the person's id, so every group carries the id as well as the key.Step 4 of 5Insert Zoe again. Her id matches no group, so she gets a new one; Ben's group, found by his id, moves down with his note.
Step 5 of 5
The building block
Android's docs say a composable's instance in the composition "is identified by its call site": the place in your source where the composable is called. Two different lines that call Counter are two call sites, told apart by their order (puzzle 1). A loop is one call site that runs many times:
Column {
for (person in people) {
PersonRow(person) // one call site, one call per person
}
}
Each PersonRow call opens a group with PersonRow's key, and the slot table holds them one after another. On the next run, the first call takes the first group, the second call the second, and so on. Nothing ties a group to a person. The docs put it plainly: when calls come from the same call site, "the execution order is used in addition to the call site".
So when Zoe is inserted at the top, the first call (now Zoe) takes the group that held Ana, the second call (now Ana) takes the one that held Ben, with the note you typed, and so on. A new group is added at the end for the last person. Each row gets new arguments, so every row runs again, and any value it remembered now shows under someone else's name. Adding at the bottom is harmless: every old row keeps its position.
The fix is to give each call an identity of its own. key() is a composable that takes one or more values and wraps the calls inside it:
for (person in people) {
key(person.id) {
PersonRow(person)
}
}
The compiler plugin turns key(person.id) { … } into a group the runtime's code calls a movable group: its key combines the position of the key call in your source with the value you passed. The runtime's own comment says it lets "the state and nodes generated by a loop to move with the composition implied by the key". So on the next run, Ben's call finds the group marked with Ben's id wherever it now sits, and moves it, slots and nodes, to its new place. Zoe's call finds no group with her id and gets a new one.
The value only has to be unique among the calls inside that loop, not across the app: "it needs to only be unique amongst the invocations of composables at the call site". Two people with the same id would share an identity, and their remembered values could cross over again.
LazyColumn takes the same idea as a parameter: items(people, key = { it.id }) { PersonRow(it) }.
Go deeperWhat if the list is only ever appended to?
A chat screen only ever adds messages at the bottom, and never inserts, removes or reorders. Does each message row need key()?
Not for correctness. Appending leaves every old row at its position, so every call finds its own group by order; only the new row gets a new group. The docs say this too: with an item added at the bottom, "Compose can reuse the instances already in the Composition since their location in the list haven't changed". Insert, remove or reorder even once, and the rows below that point shift; that's when key() matters.
The analogy
The prompt book again. A crowd scene has ten extras, and the book only says "extra 1 wears the red scarf, extra 2 the hat". One night a new extra joins at the front of the line. The stage manager hands out costumes by place in line, so the newcomer gets the red scarf, and every extra ends up in the costume of the one before. Pin a name tag on each costume (key()), and every extra gets their own, wherever they stand.
Check yourself
Sources
- Android Developers: Lifecycle of composables ("The instance of a composable in Composition is identified by its call site."; "Key Term: The call site is the source code location in which a composable is called."; "When calling a composable multiple times from the same call site, Compose doesn't have any information to uniquely identify each call to that composable, so the execution order is used in addition to the call site in order to keep the instances distinct."; "If a new movie is added to the bottom of the list, Compose can reuse the instances already in the Composition since their location in the list haven't changed"; "By wrapping a block of code with a call to the key composable with one or more values passed in, those values will be combined to be used to identify that instance in the composition. The value for a key does not need to be globally unique, it needs to only be unique amongst the invocations of composables at the call site.")
- Compose runtime source: Composer.kt ("Start a movable group. A movable group is one that can be moved based on the value of [dataKey] which is typically supplied by the [key] pseudo compiler function."; "A movable group implements the semantics of [key] which allows the state and nodes generated by a loop to move with the composition implied by the key passed to [key].")
- Compose runtime source: Composables.kt ("The key must be unique for each element in the collection, however, or children and local state might be reused in unintended ways.")
- Compose compiler plugin source: ComposableFunctionBodyTransformer.kt (visitKeyCall wraps the block in "irStartMovableGroup(expression, irJoinKeyChain(keyArgs…), scope)", whose key is "element.irSourceKey()", the position of the key call)
What you now know
Every call from a loop comes from the same call site and carries the same key, so the next run can only match the rows by their order. Insert an item at the top and each remembered value stays at its position, not with its item. Wrap the row in a key with the person's id and the runtime matches rows by that id, moving each group, slots and nodes, with its item; LazyColumn's items takes the same id as its key parameter.
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.