I am using compose-paging version 3.2.0. The get-o...
# compose
h
I am using compose-paging version 3.2.0. The get-operator on LazyPagingItems is defined like this:
Copy code
/**
 * Returns the presented item at the specified position, notifying Paging of the item access to
 * trigger any loads necessary to fulfill prefetchDistance.
 *
 * @see peek
 */
operator fun get(index: Int): T? {
    pagingDataDiffer[index] // this registers the value load
    return itemSnapshotList[index]
}
Is the any any way to avoid using the non-null operator (!!) to access items, example:
Copy code
@Composable
fun UserListContent(
    users: LazyPagingItems<UserApiModel>,
) {
    LazyVerticalGrid(columns = GridCells.Fixed(2)) {
        items(count = users.itemCount, key = { users[it]?.id!! }) { index ->
            UserListItem(user = users[index]!!)
        }
    }
}
a
Using a
!!
here looks unsafe on first look, why not just allow null as a key?
Also, getting a random index might just return
null
, that is part of the API, since you can access any index you’d like and there is no way for the list to ensure any item availability synchronously.
null
usually (with paging) means the value is currently loading.
m
if you do not use placeHolders, i believe !! is safe. But better model around the possibility of it being null regardless
i
That's not what you should be using for keys anyways - that's exactly why the
itemKey
method exists (which does give you a non-null item): https://developer.android.com/jetpack/compose/libraries#paging
That's what allows Paging to handle placeholder keys for you while you only provide keys for actual items
m
yes. good catch. I attempted sth similar long ago. That will get you in trouble and will someday crash!
h
Oh, thank you. That is exactly what I was looking for.