我正在使用第 3 页,但在可用教程中找不到我的用例。基本上我粘贴的是我在文档和所有在线教程中找到的示例,基本上backend.searchUsers(query, nextPageNumber)
不适合我的情况,我只需要打电话backend.fetchAList(userId,startRecord,endRecord)
,所以基本上我需要询问后端只给我特定范围的页面,假设我每次想要 16 个项目,我想我应该问startRecord:0 endRecord:15
然后我不知道如果用户在列表末尾滚动我应该问startRecord:16 endRecord:31
等等,直到列表末尾。如何使用 Paging3 实现这一目标?
编辑:我假设我的方法应该像我上面提到的我的用例是:作为用户,我想用 PaginatedData 检索一个列表来填充我的适配器,逐渐加载列表以便使用滚动一定数量的页面然后从后端检索新的,条件是后端有这些字段: startRecord: Int; endRecord:Int, hasNextItems: Boolean, List, totalItems: Int
class ExamplePagingSource(
val backend: ExampleBackendService,
val query: String
) : PagingSource<Int, User>() {
override suspend fun load(
params: LoadParams<Int>
): LoadResult<Int, User> {
try {
// Start refresh at page 1 if undefined.
val nextPageNumber = params.key ?: 1
val response = backend.searchUsers(query, nextPageNumber)
return LoadResult.Page(
data = response.users,
prevKey = null, // Only paging forward.
nextKey = response.nextPageNumber
)
} catch (e: Exception) {
// Handle errors in this block and return LoadResult.Error if it is an
// expected error (such as a network failure).
}
}
override fun getRefreshKey(state: PagingState<Int, User>): Int? {
// Try to find the page key of the closest page to anchorPosition, from
// either the prevKey or the nextKey, but you need to handle nullability
// here:
// * prevKey == null -> anchorPage is the first page.
// * nextKey == null -> anchorPage is the last page.
// * both prevKey and nextKey null -> anchorPage is the initial page, so
// just return null.
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
}