首先,在 Android paging3 codelab 中, getRefreshKey 实际上是用于确定是否需要获取新数据的方法。以下是一个简单的示例,以帮助解释该方法的用途:
private const val DEFAULT_PAGE_INDEX = 1
class MyPagingSource(private val apiService: ApiService) : PagingSource() {
override suspend fun load(params: LoadParams): LoadResult {
val page = params.key ?: DEFAULT_PAGE_INDEX
val response = apiService.getItems(page)
if (response.isSuccessful) {
val items = response.body()?.items ?: emptyList()
val prevKey = if (page == DEFAULT_PAGE_INDEX) null else page - 1
val nextKey = if (items.isEmpty()) null else page + 1
return LoadResult.Page(
data = items,
prevKey = prevKey,
nextKey = nextKey
)
} else {
return LoadResult.Error(Exception("Failed to load items"))
}
}
override fun getRefreshKey(state: PagingState): Int? {
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
}
在上述示例中,可以看到在 getRefreshKey
方法中实现了以下内容:
override fun getRefreshKey(state: PagingState): Int? {
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
该方法返回的是要刷新的页面的索引。页面索引具有以下属性:
要理解此示