Unless I'm overlooking the obvious, there must be ...
# compose
o
Unless I'm overlooking the obvious, there must be some secret connection between
androidx.paging.Pager
and Compose
LazyListState
. Could someone enlighten me? Details in 🧵.
In
androidx-main/frameworks/support/paging/paging-compose/samples/src/main/java/androidx/paging/compose/samples/PagingSample.kt
we have the following code (simplified):
Copy code
@Composable
fun PagingBackendSample() {
    val pager = remember {
        Pager(...) { ... }
    }

    val lazyPagingItems = pager.flow.collectAsLazyPagingItems()

    LazyColumn {
        itemsIndexed(lazyPagingItems) { index, item ->
            Text("Index=$index: $item", fontSize = 20.sp)
        }
    }
}
If my understanding is correct, if
pager.flow
wants to react to scrolling and emit new stuff on demand, it must at some point observe
LazyListState
. Yet there seems to be no explicit connection. How does
pager
find the corresponding
LazyListState
to observe?
c
The
LazyPagingItems
returned by
collectAsLazyPagingItems
notifies the pager on each call to
.get()
, prompting the load of the next value https://github.com/androidx/androidx/blob/androidx-main/paging/paging-compose/src/main/java/androidx/paging/compose/LazyPagingItems.kt#L130-L133
o
Thanks for the hint. So the pager just emits as long as someone is consuming. I’ll have to dig deeper to gain an understanding on how this works with respect to backward scrolling and caching.
Correcting myself for the record:
Pager.flow
emits just for refresh and invalidation of background data. The connection between scroll position and item fetching is • registered via the content lambda of
LazyListScope.itemsIndexed
(in
paging.compose
), • which wraps the above
get()
invocation to fetch items and registers another lambda with
LazyListScopeImpl.items
. • The latter lambda is then invoked repeatedly per element in response to scrolling.
a
Hello 👋 , I’m curious about this topic too, I hope I could get some help understanding it as well.
registered via the content lambda of
LazyListScope.itemsIndexed
(in
paging.compose
),
Does this mean it starts fetching upon
collect
? We’re trying to actually make it lazy fetch so it only fetch when the user scrolls to the section, but can’t find a way yet other than making a fake lazy
item{}
to trigger creation of the pager to collect from.
o
Using the
PagingSample.kt
mentioned above, you should see lazy fetching. Apart from that, I'm not using the Paging library, which is huge and complicated, so I cannot comment on its peculiarities. You might be seeing effects of a prefetch window size which is larger than expected, so everything gets fetched eagerly. In this case you' could try with a larger data set. But that's just a guess.