现在我正在聊天片段中使用Google分页库
这是我数据源中Initial的代码:
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);
在聊天片段中,我观察到了列表
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);
}
}
在iam尝试向分页列表中添加新消息之前,它一直运行良好,从而向我显示此错误
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);
答案 0 :(得分:1)
分页库当前不允许您向PagedAdapter中添加项目,就像对普通RecyclerView所做的那样。所有更新都必须来自数据源。
在与您类似的情况下,我执行的操作是使用Room保留所有聊天消息,并使用PagedList
(数据访问对象)中的LiveData
构建DataSource.Factory
Dao
)。每当有新消息时,您要做的就是保留该消息,然后会议室将更新发送到您的PagedList
Livedata
,并相应地更新Chats RecyclerView。
如果您不熟悉Room,可以从offical documentation
阅读更多内容