android - Android Paging 3:LoadType.APPEND 返回空远程键
问题描述
我一直在尝试解决如何解决RemoteMediator
's 的问题APPEND
LoadType
。
在空的 Room DB 上,LoadType
流程如下: REFRESH -> PREPEND -> APPEND (remoteKeys = null, endOfPaginationReached = true)
实体和远程键表至少有 10 行,LoadType
流程如下: REFRESH -> PREPEND -> APPEND (remoteKeys = prev=null, next=2, endOfPaginationReached = false)
显然,我的问题是在新安装的设备上(房间数据库为空),用户不会看到超过 10 个项目,因为APPEND
'sstate.lastItemOrNull()
正在返回null
。
到目前为止,这是我的代码:
private suspend fun getRemoteKeysForLastItem(state: PagingState<Int, MovieCache>): MovieRemoteKeys? {
return state.lastItemOrNull()?.let { movie ->
appDatabase.withTransaction {
appDatabase.remoteKeysDao().remoteKeysByImdbId(movie.imdbId)
}
}
}
对于我的load()
功能:
val loadKey = when (loadType) {
LoadType.REFRESH -> {
val key = getRemoteKeysClosestToCurrentPosition(state)
Timber.d("REFRESH key: $key, output: ${key?.nextKey?.minus(1)}")
key?.nextKey?.minus(1) ?: 1
}
LoadType.PREPEND -> {
Timber.d("PREPEND key requested")
return MediatorResult.Success(true)
}
LoadType.APPEND -> {
val key = getRemoteKeysForLastItem(state)
Timber.d("APPEND key: $key")
appDatabase.withTransaction {
val size = movieDao.movies().size
val remoteSize = remoteKeysDao.allKeys().size
Timber.d("APPEND DB size: $size, remote: $remoteSize")
}
key?.nextKey ?: return MediatorResult.Success(true)
}
}
让我的应用程序至少无法向下滚动一次!
解决方案
最后,这就是我通过依赖数据库上的 remoteKeys 来解决这个问题的方法PagingState
:
LoadType.APPEND -> {
// val key = getRemoteKeysForLastItem(state) // Doesn't work. state returns NULL even Room has data for both remote keys and entity.
val key = appDatabase.withTransaction {
remoteKeysDao.allKeys().lastOrNull() // Workaround
}
key?.nextKey ?: return MediatorResult.Success(true)
}
推荐阅读
- mysql - 在特定条件下更改值
- python - 制作多文件程序时“无法导入名称*x*”
- git - 需要不同的默认 git 用户,具体取决于项目
- elm - 为什么这个函数是这样注释的?
- windows - 如何在 cmd 或 PowerShell 中跟踪符号/软链接?
- regex - “Gedcom 文件 - 如何拆分名称和消除双位。”
- airflow - Apache Airflow - 获取所有父 task_id
- docker - 如何使用 dotnet sdk linux docker 映像和从 Windows 10 安装的卷运行 dotnet restore?
- java - Windows 10 变量中的 java 和 maven 安装
- c# - 简单的文件传输到 Azure c#