AbstractRealmResultsObserver.java 1.05 KB
Newer Older
Tiago Cunha's avatar
Tiago Cunha committed
1
package chat.rocket.persistence.realm;
2 3 4 5 6 7 8

import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmObject;
import io.realm.RealmResults;

abstract class AbstractRealmResultsObserver<T extends RealmObject> {
Yusuke Iwaki's avatar
Yusuke Iwaki committed
9
  private final RealmHelper helper;
10 11 12 13 14 15 16 17
  protected Realm realm;
  private RealmChangeListener<RealmResults<T>> listener;
  private RealmResults<T> results;

  protected AbstractRealmResultsObserver(RealmHelper helper) {
    this.helper = helper;
  }

Yusuke Iwaki's avatar
Yusuke Iwaki committed
18 19 20 21
  protected abstract RealmResults<T> queryItems(Realm realm);

  protected abstract RealmChangeListener<RealmResults<T>> getListener();

22 23 24 25 26 27 28 29 30 31 32 33
  public void sub() {
    unsub();

    realm = helper.instance();
    listener = getListener();
    results = queryItems(realm);

    listener.onChange(results);
    results.addChangeListener(listener);
  }

  public void unsub() {
34
    if (realm != null) {
35
      if (results != null) {
36 37 38
        if (results.isValid()) {
          results.removeChangeListener(listener);
        }
39 40
        results = null;
      }
41 42
      realm.close();
      realm = null;
43 44 45 46
    }
  }

}