I tried to avoid creating and managing Realm objects in an Android app for each fragment. I think ThreadLocalVariable could be a good start.
public class RealmInstanceGenerator extends ThreadLocal<Realm> { public Realm getRealmForMyThread(Context context) { if(get() == null && context != null) super.set(Realm.getInstance(context)); return get(); } public void setRealmForCurrentThread(Context context) { if(context != null) super.set(Realm.getInstance(context)); } @Override protected Realm initialValue() { return null; } @Override public void remove() { if(get() != null) get().close(); super.remove(); } }
I would just create a static target RealmInstanceGenerator in my utils singleton class and call setRealmForCurrentThread in my MainActivity. Then I will call delete when my activity dies. A new Realm object is automatically created for any new thread. Is this a good strategy?
source share