Gabor Varadi
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.

    Gabor Varadi

    Written by

    Android dev, `Zhuinden`, or ‘EpicPandaForce’ @ SO. Extension function fan #Kotlin, dislikes multiple Activities/Fragment backstack.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade