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

时间:2016-09-28 09:03:43

标签: java android realm rx-java

当我将查询结果作为observable返回时,我必须在哪里关闭realm实例?例如:

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

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

1 个答案:

答案 0 :(得分:2)

有几种情况:

  1. doOnCompleted运营商:

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

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