Sinigr Sinigr - 2 months ago 9
Java Question

Close Realm instance, when i use Realm query with RxJava

when I return query results as observable, where I must close realm instance? Example:

public Observable<RealmResults<Weather>> getWeatherForecast() {
final Realm realm = Realm.getDefaultInstance();

return realm.where(Weather.class).findAllAsync().asObservable()
.filter(RealmResults::isLoaded);
}

Answer

There are a couple of cases:

  1. doOnCompleted operator:

    realm.where(Weather.class).findAllAsync().asObservable()
            .filter(RealmResults::isLoaded)
            .first()
            .doOnCompleted(new Action0() {
                 @Override
                 public void call() {
                     realm.close();
                 };
            })
    
  2. Inside Subscriber's onCompleted method:

    getWeatherForecast()
            .subscribe(new Subscriber<Boolean>() {
                @Override
                public void onCompleted() {
                    realm.close();
                }
    
                @Override
                public void onError(Throwable e) {
    
                }
    
                @Override
                public void onNext(Boolean aBoolean) {
                }
            });
    
Comments