androidandroid-jetpack-composeandroid-paging

How LazyList can notify the pager to load more item using the jetpack paging library?


it's been a while, since I was using the paging library with the usual recyclerView , that I was curious about how can the recyclerView notify the Pager for to load new pages when they are needed. When i saw the way LazyList or LazyGrid works in compose it is even more evident that there is something to explain that the official documentation doesn't.

If we look at that simple code :

        val movies: LazyPagingItems<Movie> = viewModelInstance.moviesList.collectAsLazyPagingItems()

        Surface(color = MaterialTheme.colorScheme.background, modifier = Modifier.padding(innerPadding)) {
            LazyVerticalGrid(
                columns = GridCells.Adaptive(130.dp)
            ) {
                items(count = movies.itemCount)
                {index ->
                    movies[index]?.let {
                        MovieItemGrid(it, onMovieClicked)
                    }
                }
            }

we see here that the only way that the lazyGrid can notify the Pager class is to act on the moviesList: Flow<PagingData< Movie >>, since it is collected lazily. I guess that when the Flow , that internally is a simpleChannelFlow, completes to be collected, it signals the need for another page. I can't find the code where this happens or I could be completely wrong. Who can explain me what excatly happen ? Thank you.


Solution

  • It happens when you call movies[index] (LazyPagingItems::get). When the number of loaded items before or after the requested index is smaller than PagingConfig.prefetchDistance, paging library starts loading next page. From the get method documentation:

    Returns the presented item at the specified position, notifying Paging of the item access to trigger any loads necessary to fulfill prefetchDistance.