https://kotlinlang.org logo
#compose
Title
# compose
o

Oliver.O

02/15/2023, 1:09 PM
A question about the
LazyListScope.items
method which adds a count of (lazily loaded) items (as used by the Paging library): Is it correct to assume that the stability requirement for
key
applies to real items only and placeholder item keys may be unstable? Details in 🧵.
The documentation of
LazyListScope.items
describes its
key
parameter as
a factory of stable and unique keys representing the item. Using the same key for multiple items in the list is not allowed. Type of the key should be saveable via Bundle on Android.
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyDsl.kt;drc=4945360f3a8b2245ebf3c33d891e7e1824cb241c;l=78 My initial impression was: Supplying a stable and unique index per element would require to actually load each requested element (or at least its ID) from a data source. Doing this synchronously in the UI thread would then stall the UI, so it seemed like an unfeasible condition to fulfill. (And
LazyListItemProvider
would frequently request a large sliding window of item keys near the first visible item.) Now it seems that the stability and uniqueness requirement does not apply to placeholder items. In `androidx.paging.compose`'s
LazyPagingItems.kt
, the
key
parameter is initialized as follows:
Copy code
key = if (key == null) null else { index ->
            val item = items.peek(index)
            if (item == null) {
                PagingPlaceholderKey(index)
            } else {
                key(index, item)
            }
        }
Consider having 20 items in total, 5 of those visible, with the first visible item at index 10. Let's assume only the visible items will be actually loaded from the data source. So there are 10 placeholder keys [0..9], followed by 5 real item keys [10..14], followed by 5 placeholder keys [15..19]. • Now I insert 5 elements before index 0. The placeholder keys [0..5] would now be created for the 5 newly inserted items, so at this point, these keys, having pointed to other placeholder items before, are not stable. (The previously existing placeholders [0..9] would "move" to [5..14]. The first visible item would move to 15.) • Now the first visible item changes from 15 to 10. The placeholder keys [10..14] change to real item keys. Both scenarios prompted my above question: Is it correct to assume that the stability requirement for
key
applies to real items only and placeholder item keys may be unstable? If the above assumption is correct, could the API be simplified by allowing the
key
factory to return a
null
value for placeholder items, and implementing the
PagingPlaceholderKey
mechanism inside
LazyListScope
(although this would probably have to be a non-
Parcelable
implementation)?
106 Views