clueless_noob
clueless_noob

Reputation: 1

Pattern for persisting data in Realm?

My issue is how to organize the code. Let say I have a User class

public class User extends RealmObject {
    @PrimaryKey
    private String id;
    @Required
    private String name;

    public User() { // per requirement of no args constructor
        id = UUID.randomUUID().toString();
    }

    // Assume getter & setter below...
}

and a Util class is needed to handles the save in an asynchronous manner since RealmObjects cannot have methods other than getter/setter.

public class Util {
    public static void save(User user, Realm realm) {
        RealmAsyncTask transaction = realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.copyToRealm(user);  // <====== Argument needs to be declared final in parent method's argument!
            }
        }, null);
    }
}

The intention is to put save() in a Util class to prevent spreading similar save code all over the code-base so that every time I wanted to save I would just call it as such:

User u = new User();
u.setName("Uncle Sam");
Util.save(u, Realm.getDefaultInstance());

Not sure if this affects performance at all, but I was just going to save all fields overwriting what was there except for the unique id field every single time.

The problem is that I now need to set the "user" argument as final in the Util.save() method, which means I cannot pass in the object I need to save other than once.

Is there a different way of handling this? Maybe a different pattern? Or am I looking at this all wrong and should go back to SQLite?

Upvotes: 0

Views: 1005

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

Why is it a problem to set public static void save(final User user, Realm realm) ? It just means you cannot reassign the user variable to something else.

That said, the existence of a save() method can be a potential code smell as you then spread the update behaviour across the code base. I would suggest looking into something like the Repository pattern (http://martinfowler.com/eaaCatalog/repository.html) instead.

Realm is actually working on an example showing how you can combine the Model-View-Presenter architecture with a Repository to encapsulate updates which is a good pattern for what you are trying to do here. You can see the code for it here: https://github.com/realm/realm-java/pull/1960

Upvotes: 1

Related Questions