I am using RemoteMediator in my android compose project.
我在我的Android Compose项目中使用RemoteMediator。
The implementation looks something like:
该实现类似于:
@OptIn(ExperimentalPagingApi::class)
class MessagesRemoteMediator(
private val db : MessagesDB,
private val messageService : MessageService,
private val query : Long
) : RemoteMediator<Int, MessageDb>() {
override suspend fun initialize(): InitializeAction {
// checking if refresh is needed
...
}
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, MessageDb>
): MediatorResult {
return try {
val response = when (loadType) {
LoadType.REFRESH -> {
messageService.refreshChatMessages(query)
}
LoadType.PREPEND -> {
//add new messages to start of reversed list
val firstItem = state.firstItemOrNull()
?: return MediatorResult.Success(endOfPaginationReached = true)
messageService.getNewChatMessages(firstItem.timeStamp, query)
}
LoadType.APPEND -> {
// add older messages to end of reversed list
val lastItem = state.lastItemOrNull()
?: return MediatorResult.Success(endOfPaginationReached = true)
messageService.getOldChatMessages(lastItem.timeStamp, query)
}
}
db.withTransaction {
db.dao.insertNewMessages(response.map {dto ->
dto.toMessageDb()
})
}
//Does not work without delay
if(loadType == LoadType.REFRESH)
delay(3000)
MediatorResult.Success(endOfPaginationReached = response.isEmpty())
} catch (e: Exception){
Log.d("CHECKTAGS", e.stackTraceToString())
MediatorResult.Error(e)
}
}
}
I am getting response from my server on initial refresh. And new data is inserted in Room's db. Still, prepend and append calls bump into null checks and pagination stops.
我在初始刷新时收到来自服务器的响应。并将新数据插入到Room的数据库中。尽管如此,Preend和Append调用仍会遇到空检查和分页停止。
It does work if I add delay after initial refresh. Is there a problem in remote mediator's code, or issue could be with lazy column in compose function?
如果我在初始刷新后添加延迟,它确实起作用。是远程中介器的代码有问题,还是组合函数中的惰性列有问题?
Update
Recreating project on XML gives same result.
Guess I could rely on db keys solution, described here
post
在XML上更新重新创建项目会产生相同的结果。我想我可以依靠db key解决方案,这里的帖子描述了
Still I don't understand why lastItemOrNull() does not work. For initial population of db I do not use it. It is being called only after initial data is being saved to room.
不过,我还是不明白为什么lastItemOrNull()不起作用。对于数据库的初始群体,我不使用它。只有在将初始数据保存到房间后才会调用它。
更多回答
优秀答案推荐
我是一名优秀的程序员,十分优秀!