0

This question is the sequel of my previous one : Is it safe to use ActiveRecord pattern with Realm?

Is it safe to use convenient static getters like this one ?

public static List<ItemRealm> getListByBar(String bar){
    Realm realm = Realm.getDefaultInstance();
    RealmResults<ItemRealm> rtn = realm.where(ItemRealm.class).equalTo("foo", bar).findAll();
    //realm.close();
    return rtn;
}

By the comments on my previous post, it seems I should close the realm, but if I do my item are no longer usable.

For this is a request I make very often in my code, I want to have a delegated method.

What is the recommanded way to do so ?

Community
  • 1
  • 1
Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92

1 Answers1

0

It's only safe if your Realm lifecycle is managed outside of this method.

public static List<ItemRealm> getListByBar(Realm realm, String bar) {
    //Realm realm = Realm.getDefaultInstance();
    return realm.where(ItemRealm.class).equalTo("foo", bar).findAll();
    //realm.close();
}

Although I wonder how you intend to keep it synchronized if you expose it as a List<> and therefore cannot add a RealmChangeListener.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • For this use, I dont really need RealmChangeListeners. But isn't it a problem for every `findAll()` uses ? – Dan Chaltiel Apr 04 '17 at 11:21
  • I'm not sure I understand the question, but if the results get updated, you can't seem to get notified about it this way. – EpicPandaForce Apr 04 '17 at 11:44
  • I meant this is a problem with `findAll()` which returns a List, not a problem with the delegated static method, isn't it ? – Dan Chaltiel Apr 04 '17 at 12:36
  • if the results get updated, you can't seem to get notified about it this way. Please check [my other answer about getting notified by changes to the results](http://stackoverflow.com/questions/43192015/realm-working-with-clean-architecture-and-rxjava2/43202425#43202425) – EpicPandaForce Apr 04 '17 at 12:44