I have the following code, but I don't think the pagination is implemented.
dao
interface IArticleDao {
@Query(
"""
SELECT * FROM t_article ORDER BY :order DESC
"""
)
fun pagingSource(order: String): PagingSource<Int, Article>
}
Repository
class ArticleRepository @Inject constructor(
private val articleDao: IArticleDao
) {
fun list(order: String) = articleDao.pagingSource(order)
}
ViewModel
@HiltViewModel
class ArticleViewModel @Inject constructor(private val articleRepository: ArticleRepository) : ViewModel() {
fun list(order: String) = Pager(PagingConfig(pageSize = 20)){
articleRepository.list(order)
}.flow.cachedIn(viewModelScope)
}
Screen
val articleViewModel = hiltViewModel<ArticleViewModel>()
val lazyArticleItem = articleViewModel.list("id").collectAsLazyPagingItems()
ArticlePage(lazyArticleItem)
ArticlePage
LazyColumn{
items(...)
when(val state = lazyArticleItem.loadState.append){
is LoadState.Error -> {
println("error")
}
is LoadState.Loading -> {
println("${lazyArticleItem.itemCount}, ${lazyArticleItem.itemSnapshotList}")
}
else -> {}
}
}
lazyArticleItem.itemCount
printed the number 668, so I don't think the pagination is working properly, but the data displayed on the UI interface is fine, it's just not paginated by 20 items per page.
In the PagingConfig
, you can specify enablePlaceholders
, which is true by default (your case). If placeholders are enabled and paging source knows the total number of items, which it knows when it takes data from room database, lazyArticleItem.itemSnapshotList
size will be the total size of the source, only the elements that are not yet loaded will be null
.
So you can't say that paging is not working based on itemCount
. You are also printing itemSnapshotList
, are there null
s? You can also try setting enablePlaceholders = false
, itemCount
then corresponds to the number of loaded items.