在使用Paging 3进行分页时,我们可能会遇到在LoadType.APPEND时返回null的远程键值的问题。此时,我们需要检查以下几点:
- RemoteMediator对象中的load函数是否正确返回远程键值。在该函数中,我们需要获取最后一条加载数据的键值,并将其返回。
示例代码:
override suspend fun load(loadType: LoadType, state: PagingState): MediatorResult {
val page = when (loadType) {
LoadType.REFRESH -> {
// This is triggered by a swipe-to-refresh.
// Don't use remote key since refresh will clear all data.
null
}
LoadType.PREPEND -> {
// This is triggered when the user scrolls to the top of the list.
// We should use the first available remote key, which is closest to the position.
val remoteKeys = getClosestRemoteKeys(state)
remoteKeys?.prevKey ?: return MediatorResult.Success(endOfPaginationReached = !remoteKeys.isNullOrEmpty())
}
LoadType.APPEND -> {
// This is triggered when the user scrolls to the end of the list.
// We should use the last available remote key, which is closest to the position.
val remoteKeys = getClosestRemoteKeys(state)
remoteKeys?.nextKey ?: return MediatorResult.Success(endOfPaginationReached = !remoteKeys.isNullOrEmpty())
}
}
// ...
val apiResponse = service.getData(page ?: 1)
val items = apiResponse.data
val endOfPaginationReached = items.isEmpty()
// ...
val keys = items.map {
RemoteKeys(repoId = it.id, prevKey = page, nextKey = page)
}
db.remoteKeysDao().insertAll(keys)
return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
}
-
在刷新(LoadType.REFRESH)时,不要使用远程键值(remote key)。因为刷新将清除所有数据,打破了该键与数据的对应关系。
-
在LoadType.PREPEND时,使用最接近位置的第一个可用远程键值(closest available remote key)。如果没有可用的键值,则返回success状态即可。
-
在LoadType.APPEND时,使用最接近位置的最后一个可用远程键值(closest available remote key)。如果没有可用的键值,则返回success状态即可。