1

我正在尝试使用Android Paging Library 3实现基于光标的分页(基于GraphQL Relay 规范) ,但我不知道如何实现。getRefreshKey

这是我尝试过的:

data class PagingKey(
    val before: String? = null,
    val after: String? = null,
)

class MoviePagingSource() : PagingSource<PagingKey, Movie>() {
    override suspend fun load(params: LoadParams<PagingKey>): LoadResult<PagingKey, Movie> {
        return try {
            val response = fetchMovies(
                before = params.key?.before,
                after = params.key?.after,
                pageSize = params.loadSize,
            )

            LoadResult.Page(
                data = response.edges.map { mapEdgeToMovie(it) },
                prevKey = if (response.pageInfo.hasPreviousPage) PagingKey(
                    before = response.pageInfo.startCursor
                ) else null,
                nextKey = if (response.pageInfo.hasNextPage) PagingKey(
                    after = response.pageInfo.endCursor
                ) else null,
            )
        } catch (exception: Exception) {
            LoadResult.Error(exception)
        }
    }

    override fun getRefreshKey(state: PagingState<PagingKey, Movie>): PagingKey? {
        // TODO: What to return here?
    }
}

在所有示例中,我可以发现页码只是递增/递减,但这不适用于游标。

实现这一点的正确方法是什么?


在这被错误地标记为重复之前,我已经看到了这个问题。这不能回答我的问题,因为他们的 API 被称为而不是像上面那样service.getOrders(query, params.key ?: "", 10)单独的before/after参数。fetchMovies

4

1 回答 1

0

您可以做的是获取要重新加载的页面的索引,然后转到下一页获取prevKey或上一页获取nextKey.

 override fun getRefreshKey(
    state: PagingState<PagingKey, Movie>,
): PagingKey? {
    return state.anchorPosition?.let { anchorPosition ->
        val anchorPageIndex = state.pages.indexOf(state.closestPageToPosition(anchorPosition))
        state.pages.getOrNull(anchorPageIndex + 1)?.prevKey ?: state.pages.getOrNull(anchorPageIndex - 1)?.nextKey
    }
}
于 2021-08-11T11:53:59.750 回答