I'm feching pagination data using Paging3 in Compose. When I trigger refresh and the list is in the middle of two pages (the page size is 20 items and the scroll is between 17 and 21) the list shows the item 21 and the loading on top and bottom. After that the scroll reset to the top of the first page. When the scroll is not in the middle of two pages I have no problem.
I guess the paging is loading pages 1,2,3 but why the page 2 keeps the items in screen and page 1 and page 3 show loading??
Is this the expected behaviour?? is a bug? Did I miss something in the configuration?
My PagingSource:
class GenericPagingDataSource<ITEM : Any, RAW_ITEM, RESPONSE : ResponseListRaw<RAW_ITEM>> (
private val networkCall: suspend (Int) -> Result<RESPONSE, NetworkError>,
private val mapItemList: (List<RAW_ITEM>) -> List<ITEM>
) : PagingSource<Int, ITEM>() {
private var nextPageNumber: Int = 1
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ITEM> {
nextPageNumber = params.key ?: 1
return when (val response = networkCall.invoke(nextPageNumber)) {
is Result.Success -> {
try {
val items = mapItemList(response.data.results)
val prevKey = response.data.page - 1
val nextKey = response.data.page + 1
LoadResult.Page(
items,
if (prevKey < 1) null else prevKey,
if (items.isEmpty()) null else nextKey
)
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
Timber.e(e, "Mapping error in pagination")
LoadResult.Error(Exception())
}
}
is Result.Error -> {
LoadResult.Error(Exception())
}
}
}
override fun getRefreshKey(state: PagingState<Int, ITEM>): Int? {
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
}
How I request the data:
override fun getListItems(listId: Long): Flow<PagingData<MediaItem>> {
return Pager(
config = PagingConfig(
pageSize = 20,
enablePlaceholders = false,
),
pagingSourceFactory = {
GenericPagingDataSource(
networkCall = { page ->
listRemoteDataSource.getListItems(
listId = listId,
page = page
)
},
mapItemList = {
it.toModel(
baseUrlPoster = urlProvider.BASE_URL_POSTER,
baseUrlBackdrop = urlProvider.BASE_URL_BACKDROP
)
}
)
}
).flow
}