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)
}
}
}
I resolve this issues by returning null in the getRefreshKey()
method