Search code examples
androidrealm

Single Object in Realm


I want to persist object of User in Realm, and I want to persist only single object and get it everywhere like singleton UserProfile.getInstance().

So how to implement it?

I do it using dirty approach (as I mind)

public static User getInstance() {
    Realm realm = Realm.getDefaultInstance();
    User user = realm.where(User.class).findFirst();
    if (user != null) {
        // If object exists in db
        return user;
    }

    // If object does not exist, we should to create it
    realm.executeTransaction(realm -> {
        realm.insertOrUpdate(new User());
    });

    // After create we should to return already 'managed' object.
    return realm.where(User.class).findFirst();
}

This code smells bad, but I not found any better solution. Also I not found any useful information in official docs.

How do you implement singleton objects in Realm?


Solution

  • Since this is a Singleton you can use copyToRealm instead of copyOrUpdate which infers that you want to update the user (defies the goal you're trying to achieve).

    class Foo {
        private volatile User user = null;
        public User getInstance() {
            if (user == null) {
                synchronized(this) {
                    if (user == null)
                    // If object does not exist, we create it
                    realm.executeTransaction(realm -> {
                        user = realm.copyToRealm(new User());
                    });
                }
            }
            return user;
        }
    }
    

    Note the use of copyToRealm instead of insertToRealm since copy* methods will return the managed object (no need to query for it again).