Orbit
Orbit

Reputation: 2395

Using Realm with RxJava 2

I am using RxJava 2 in my Android application, and am integrating Realm. As far as I can tell, Realm only supports RxJava 1 by default, and allows an Observable to be returned when querying for RealmResults<?>, like so:

Realm.getDefaultInstance()
    .where(VideoBundle.class)
    .findAll()
    .asObservable()
    .first()

The Observable returned is from RxJava 1. How can I use Realm and RxJava 2 together? I have come across 2 relevant issues, found here and here, but no succinct answer was found. Additionally, the documentation (found here: https://realm.io/docs/java/latest/#rxjava) mentions creating a custom RxObservableFactory, but provides no resources on how to do so.

How can Realm be used with a project already using RxJava 2?

Upvotes: 2

Views: 4973

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81588

The solution is to wrap RealmResults with Flowable, with LATEST backpressure strategy.

private io.reactivex.Flowable<RealmResults<_>> getSomeItems() {
    return io.reactivex.Flowable.create(new FlowableOnSubscribe<RealmResults<__>>() {
        @Override
        public void subscribe(FlowableEmitter<RealmResults<__>> emitter)
                throws Exception {
            Realm realm = Realm.getDefaultInstance();
            RealmResults<__> results = realm.where(__.class).findAllSortedAsync("__");

            final RealmChangeListener<RealmResults<__>> listener = _realm -> {
                if(!emitter.isUnsubscribed() && results.isLoaded()) {
                     emitter.onNext(results);
                }
            };
            emitter.setDisposable(Disposables.fromRunnable(() -> {
                results.removeChangeListener(listener);
                realm.close();
            }));
            results.addChangeListener(listener);
        }
    }, BackpressureStrategy.LATEST)
    .subscribeOn(AndroidSchedulers.mainThread())
    .unsubscribeOn(AndroidSchedulers.mainThread());

From Realm 4.0.0-RC1 and above, this behavior I showed above is baked in using realmResults.asFlowable().

Disposable subscription = realm.where(__.class)
                               .findAllSortedAsync("__")
                               .asFlowable()
                               .filter(RealmResults::isLoaded)
                               .subscribe(...);

Upvotes: 3

Related Questions