Karim Ata
Karim Ata

Reputation: 343

How to add item to paged list

Now I'm using Google paging library in chat fragment

Here's code inside initial in my data source:

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);

And in chat fragment I observe the list

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);
        }
    }

It working well until I'm trying to add new message to paged list so it show me this error

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

When I get new message I try to add it as this

messages.add(0, message);

Upvotes: 2

Views: 3938

Answers (1)

Networks
Networks

Reputation: 2212

The Paging Library doesn't currently allow you to add items to the PagedAdapter like it is done for the normal RecyclerView. All updates must come from the datasource.

What I did in a similar situation to yours is persist all chat messages using Room and build the PagedList LiveData with a DataSource.Factory from the Dao(Data Access Object). Whenever there is a new message, all you have to do is persist that message,then room sends the update to your PagedList Livedata and your Chats RecyclerView updates accordingly.

If you are unfamiliar with Room you can read more from the offical documentation

Upvotes: 3

Related Questions