I was trying to avoid creating and managing Realm objects, in my android application, for every fragment. I am thinking ThreadLocalVariable might 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 final object of RealmInstanceGenerator in my utils singleton class and call setRealmForCurrentThread in my MainActivity. Then I will call remove when my activity dies. For any new thread a new Realm object will be automatically generated. Is it a good strategy ?
Christian from Realm here. It is a good strategy, and luckily we already implemented it for you :) All Realm instances are already being cached in a ThreadLocal and we keep track of instances using a counter. The Realm is only fully closed once the counter reaches 0.
This means as long as you always calls close() (which you should), it is effectively the same as your remove() method.
You can see the pattern used in this example here: https://github.com/realm/realm-java/tree/master/examples/threadExample/src/main/java/io/realm/examples/threads
And the source code for the Realm class is here: https://github.com/realm/realm-java/blob/master/realm/src/main/java/io/realm/Realm.java