关闭Realm实例,当我使用RxJava的Realm查询



当我返回查询结果作为可观察的,在哪里我必须关闭领域实例?例子:

public Observable<RealmResults<Weather>> getWeatherForecast() {
       final Realm realm = Realm.getDefaultInstance(); 
       return realm.where(Weather.class).findAllAsync().asObservable()
                .filter(RealmResults::isLoaded);
}

有两种情况:

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

相关内容

  • 没有找到相关文章

最新更新