Reputation: 91
I am trying to figure out what is the best way to open/close Realm instances. We are using Realm in 3 places - App, Activities and Worker thread. However, it might be pretty cool to access data from Realm from any place. Thus, we wrapped all our Realm queries/writes in a Data Layer. Is it ok (from performance point of view) to do the following for every query (and similar on each write)?
try (Realm realm = getRealm()) {
return realm.copyFromRealm(realm.where(Task.class).isNull("name")
.findAllSorted("createdAt", Sort.DESCENDING));
}
How do you do something similar in async transaction? Are there better approaches? (We are using RxJava).
Thank you!
EDIT: After quick response from @christian-melchior we will use it like this:
try (Realm realm = getRealm()) {
return realm.copyFromRealm(realm.where(Task.class).isNull("name")
.findAllSortedAsync("createdAt", Sort.DESCENDING));
}
EDIT2: We actually settled on this:
Realm realm = getRealm();
return realm.where(Task.class).isNull("name")
.findAllSortedAsync("createdAt", Sort.DESCENDING)
.asObservable()
.filter(RealmResults::isLoaded)
.first()
.map(realmObjects -> {
if (realmObjects.isEmpty()) {
realm.close();
return null;
}
List<Task> res = realm.copyFromRealm(realmObjects);
realm.close();
return res;
});
Since we want our onComplete
to be called after each query.
Upvotes: 1
Views: 2835
Reputation: 20126
Using copyFromRealm
will give you an in-memory copy of all the data, so as long as you are not loading huge lists, it should work fine. You will use more memory though, and there is a slight overhead in opening and closing Realms all the time.
One idea for controlling the Realm lifecycle can be seen here: https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances
Also note you in many cases can use our async API if you are concerned about loading data on the UI thread: https://realm.io/docs/java/latest/#asynchronous-queries
Upvotes: 1