LazyList keys - it helps to restore the scroll pos...
# compose
s
LazyList keys - it helps to restore the scroll position. Apart from that, does it has any other uses? I heard using key will prevent unwanted recomposition. If yes, how does it works? what if the key has not changed but the content has been changed? And how is it different from contentType lamda?
t
From what I recall (and please correct me if I'm wrong) the keys are used to avoid recompositions in situations where the order of items in the LazyList changes. Compose uses positional memoization of nodes, meaning that the order in which a composable is defined is used to know what the previous inputs to that node were. Say we have a LazyList with the following items:
Copy code
- MyComposable("foo")
- MyComposable("bar")
Compose will "remember" that the first instance of MyComposable receives "foo" as a parameter while the second one receives "bar". If we now add a new item to the list, the first two composable's inputs will not have changed and Compose can (potentially) skip recomposition, requiring only the new item to be composed.
Copy code
- MyComposable("foo")
- MyComposable("bar")
- MyComposable("baz")
If we now change the order in which these elements appear, however, Compose can no longer easily skip recomposition. Say the user drags and reorders the list as follows:
Copy code
- MyComposable("foo")
- MyComposable("baz")
- MyComposable("bar")
The first composable's recomposition can be skipped given that its input has not changed, while the second and third no longer have the same input. Had we provided a unique key to each of these composables, however, Compose could still figure out that no new items had been added and that only the order of elements has changed. This in theory allows Compose to skip recomposition for each of these nodes. About the contentType lambda, I'm not quite sure whether I'm understanding this correctly but from what I can read from the docs it seems that the contentType allows Compose to reuse composables that have scrolled off-screen for new nodes that have the same contentType (similar to how a RecyclerView would work). This allows Compose to only recompose the composable with different parameters instead of having to create it from scratch. Hope that clears things up (and that I'm not misinforming anyone 😅)
s
Got it. Thanks a lot 🙂
t
Keys are also important for animations. E.g.: when you remove one item and want to have a smotth animation. Make sure that every item has a unique key.
103 Views