现在我在聊天 fragment 中使用谷歌分页库
这是我的数据源中初始的代码:
Disposable disposable = apiWrapper.getMessages(1, userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(messagesPagingResponse -> {
if (messagesPagingResponse.getData() != null && messagesPagingResponse.getData().getData() != null) {
callback.onResult(messagesPagingResponse.getData().getData(), null, messagesPagingResponse.getData().getNextPage());
}
}
, throwable -> {
Log.e("throwable", throwable.getLocalizedMessage());
});
compositeDisposable.add(disposable);
在聊天 fragment 中我观察列表
viewModel.getLiveMessages().observe(this, this::setChatList);
private void setChatList(PagedList<Message> messages) {
this.messages = messages;
ChatPagingAdapter chatPagingAdapter = (ChatPagingAdapter) binding.messagesRecyclerView.getAdapter();
if (chatPagingAdapter != null){
chatPagingAdapter.submitList(this.messages);
}
}
它运行良好,直到我尝试将新消息添加到分页列表中,所以它向我显示此错误
E/error: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.UnsupportedOperationException
当我收到新消息时,我尝试将其添加为这样
messages.add(0, message);
最佳答案
分页库当前不允许您像普通 RecyclerView 那样向 PagedAdapter 添加项目。所有更新都必须来自数据源。
我在与您类似的情况下所做的就是使用 Room 保留所有聊天消息,并使用 DataSource.Factory
构建 PagedList
LiveData
来自Dao
(数据访问对象)。每当有新消息时,您所要做的就是保留该消息,然后 Room 将更新发送到您的 PagedList
Livedata
并且您的 Chats RecyclerView 也会相应更新。
如果您不熟悉 Room,您可以从 offical documentation 阅读更多内容。
关于android - 如何将项目添加到分页列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58852522/