[英]Android Paging3 insertSeparators doesn't work as intended
[英]Can't understand code of getRefreshKey in Android paging3 codelab
// GitHub page API is 1 based: https://developer.github.com/v3/#pagination
private const val GITHUB_STARTING_PAGE_INDEX = 1
class GithubPagingSource(
private val service: GithubService,
private val query: String
) : PagingSource<Int, Repo>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
val position = params.key ?: GITHUB_STARTING_PAGE_INDEX
val apiQuery = query + IN_QUALIFIER
return try {
val response = service.searchRepos(apiQuery, position, params.loadSize)
val repos = response.items
val nextKey = if (repos.isEmpty()) {
null
} else {
// initial load size = 3 * NETWORK_PAGE_SIZE
// ensure we're not requesting duplicating items, at the 2nd request
position + (params.loadSize / NETWORK_PAGE_SIZE)
}
LoadResult.Page(
data = repos,
prevKey = if (position == GITHUB_STARTING_PAGE_INDEX) null else position - 1,
nextKey = nextKey
)
} catch (exception: IOException) {
return LoadResult.Error(exception)
} catch (exception: HttpException) {
return LoadResult.Error(exception)
}
}
// The refresh key is used for subsequent refresh calls to PagingSource.load after the initial load
override fun getRefreshKey(state: PagingState<Int, Repo>): Int? {
// We need to get the previous key (or next key if previous is null) of the page
// that was closest to the most recently accessed index.
// Anchor position is the most recently accessed index
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
}
这是getRefreshKey
codelab的getRefreshKey function的代码。
我认为返回state.anchorPosition
就可以了。 但是为什么这个返回closestPagetToPosition的前一个键加1呢? 这是分页 3 代码实验室的链接。
好吧, state.anchorPosition
是您在此列表中看到的第一项的索引, getRefreshKey
应该返回要在刷新时加载的密钥。
在此示例中,键是页面的索引,并且每个页面通常包含许多项目,比如说 20。现在加载两个页面意味着使用键 1 和 2 并加载了 40 个项目。
在这种情况下,当您查看索引 30 上的项目时, state.anchorPosition
也是 30,但您绝对不希望刷新键为 30,您需要它为 2,因为索引 30 上的项目来自页面2. 这是最接近的closestPageToPosition
所做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.