Jul 25, 2017 · 1 min read
The try(Realm realm = Realm.getDefaultInstance()) { … } is primarily useful for opening-closing the Realm on background threads.
On UI thread, the onCreate()/onDestroy() is the right choice.
As you need to make sure you can use a Realm that belongs to any thread in your data access methods, the default recommendation is to pass the Realm instance to the method.
public static User getUser(Realm realm) {
return realm.where(User.class).equalTo(“uID”,
SyncUser.currentUser().getIdentity()).findFirst();
}Another trick that I had never thought of was to create unscoped repository that is initialized with the current Realm instance when you need it, but that makes most sense only in Kotlin. This is based on the article here.
public class UserDao {
public UserDao(Realm realm) {
this.realm = realm;
}
}public class RealmUtils {
public static UserDao userDao(Realm realm) {
return new UserDao(realm);
}
}
But I haven’t really done that before. I just pass the Realm instance to the repository method.
