Luong Dinh
Luong Dinh

Reputation: 569

RealmRecylerAdapter with RxJava

With the following code. I expect:

1. Get all the data from the server side.

2. Insert all the data to Realm

3. Refresh RecycleView with Realm Adapter.

The first time, the data is always empty. Maybe the data is still not ready but subscribe is still invoked? Is there any way to update the view when the data is ready?

ApiCall().doOnNext(response -> {
    Realm realm = Realm.getDefaultInstance();
    try {
        realm.beginTransaction();
        realm.insertOrUpdate(response);
        realm.commitTransaction();
    } finally {
        realm.close();
}
}).subscribeOn(Schedulers.io())
  .unsubscribeOn(Schedulers.computation())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new exObserver<List<T>>() {
      @Override
      public void onResponse(List<T> response) {
          updateView()
      }
      @Override
      public void onFailure(exException exception) {
          adapter.notifyChanged();
      }
});

Upvotes: 1

Views: 88

Answers (3)

Benito Bertoli
Benito Bertoli

Reputation: 25803

As EpicPandaForce mentioned, you don't need to notify RealmRecyclerViewAdapter when there is a change.

My answer will specifically target your use of RxJava.

doOnNext() is a side-effect method. This means it will be called parallel to your stream, without affecting it.

When your api call returns, the Action1 in doOnNext() and the Observer in subscribe() will both be triggered at the same time.

This means updateView() is called before the Realm transaction finishes.

If you want to update your view after inserting into the DB, your transaction must happen in your stream.

You could use flatMap() for this purpose.

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81588

RealmRecyclerViewAdapter already observes the provided data set with a RealmChangeListener, and calls adapter.notifyDataSetChanged() when a change happens in the underlying Realm.

Why are you trying to manually call adapter.notifyDataSetChanged()? The RealmRecyclerViewAdapter was specifically created so that you don't need to do that.

Upvotes: 1

Alex Shutov
Alex Shutov

Reputation: 3282

What is your apiCall() method? try using Observable.defer(()-> apicall()) if you're not using Retrofit. This will delay code evaluation until actual value arrive.

Upvotes: 0

Related Questions