7

我一直在尝试解决如何解决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)
            }
        }

APPEND这是一个示例 logcat 显示null 在此处输入图像描述

让我的应用程序至少无法向下滚动一次!

编辑:这是我保存远程密钥的方法: 在此处输入图像描述

4

1 回答 1

1

最后,这就是我通过依赖数据库上的 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)
}

于 2021-03-26T09:26:48.037 回答