I want paginated with paging3 libaray in jetpack compose.
I can use the paging3 library on one column. but, i want to use it in multiple columns. Like LazyColumn in HorizontalPager.
The model used for paging is the same.
ex. Usermodel
data class UserModel(
val name:String,
val grade:Int
)
ViewModel
val userItemPager = _page.flatMapLatest {
Pager(PagingConfig(pageSize = 20)) {
UserItemPagingSource(repoSearchImpl, it)
}.flow
}.cachedIn(viewModelScope)
PagingSource
class UserItemPagingSource(
private val repo: RepoSearch,
private val page:Int
) : PagingSource<Int, UserModel>() {
private val STARTING_KEY: Int = 0
override fun getRefreshKey(state: PagingState<Int, UserModel>): Int {
return ((state.anchorPosition ?: 0) - state.config.initialLoadSize / 2).coerceAtLeast(0)
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UserModel> {
val position = params.key ?: 0
val response = repo.load(position)
val realItem = response.filter { it.grade == page }
return try {
LoadResult.Page(
data = realItem ,
prevKey = null,
nextKey = position + realItem.size
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
HorizontalPager
val userPagingItems= viewModel.userItemPager.collectAsLazyPagingItems()
HorizontalPager(
count = Grade.values().size,
state = pagerState,
modifier = Modifier.fillMaxWidth()
) { page ->
val reaItems = remember(page) {
derivedStateOf {
userPagingItems.itemSnapshotList.filter { it?.grade == page }
}
}
GridPage(
items = reaItems,
page = page,
)
}
Inside columns
@Composable
fun GridPage(
items : State<List<UserModel?>>,
page: Int,
) {
LazyVerticalGrid(
columns = GridCells.Fixed(2),
modifier = Modifier.fillMaxSize(),
) {
items(items.value) { model ->
model?.let {
Text(text = "${model.name,model.grade}")
}
}
}
}
Divide tabs according to userModel grade(1,2,3 -> total three tap).
I want to do paging differently according to the grade.
The above code separates the tabs, but does not load.
another code
@Composable
fun GridPage(
items : LazyPagingItems<UserModel>,
page: Int,
) {
LazyVerticalGrid(
columns = GridCells.Fixed(2),
modifier = Modifier.fillMaxSize(),
) {
items(items.count) { index ->
val model = items[index]
model?.let {
Text(text = "${model.name,model.grade}")
}
}
}
}
This code loads when I scroll, but all the grades are displayed in one tab, and I don't know how to divide the tabs according to the grades.
How can I classify and paginate according to tabs?