3

I'm using below paging source implementation to fetch data from network and observing it in composable via collectAsLazyPagingItems(). However, when calling refresh() method on this LazyPagingItems, it is not fetching data from page 0 and instead fetch data from last fetched page number, which is resulting in no data to display. What's wrong here? Could it be because of val page = params.key ?: 0 ?

class CommentDataSource(
    private val postId: Long,
    private val commentApi: CommentApi
) : PagingSource<Int, Comment>() {
    override fun getRefreshKey(state: PagingState<Int, Comment>): Int? {
        return state.anchorPosition
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Comment> {
        return try {
            val page = params.key ?: 0
            val responseData = commentApi.getPostComments(
                postId = postId,
                page = page
            ).data

            LoadResult.Page(
                data = responseData.comments,
                prevKey = if (page == 0) null else page - 1,
                nextKey = if (!responseData.hasNextPage) null else responseData.currentPage + 1
            )
        } catch (e: IOException) {
            LoadResult.Error(e)
        } catch (e: HttpException) {
            LoadResult.Error(e)
        }
    }
}
Annon
  • 633
  • 7
  • 26

2 Answers2

8

I resolve this issues by returning null in the getRefreshKey() method

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Frank Mung No
  • 490
  • 1
  • 4
  • 9
0

This resolved the issue for me. Use this in your PagingSource

override fun getRefreshKey(state: PagingState<Int, DiscountModel>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }