How to use the Kingdom

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?

+5
source share
1 answer

Kingdom Christian is here. This is a good strategy, and, fortunately, we have already implemented it for you :) All instances of Realm are already cached in ThreadLocal, and we track instances using a counter. The kingdom only closes completely when the counter reaches 0.

This means that as long as you always call close () (what you need), it actually matches the remove () method.

You can see the template 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

+20
source

Source: https://habr.com/ru/post/1210394/


All Articles