Repositories with Realm

Realm 0.87 (for Android) came with a very important change: It introduced detached copies of RealmObjects. You can create a detached object using Realm.copyFromRealm. Any setter operation on a detached object won’t update the database so they can be called without opening a Realm transaction. In addition the detached objects are accessible from any thread.

We refactored our app code to use repositories and setup the following rules:

  • The UI only fetches realm objects via a repository (no more Realm code in Activities).
  • Repositories always return detached objects
  • Detached objects have to be saved using the save method in the repository.

Here’s a simple example repository:

public FooRepository {
    private Realm realm;
    public FooRepository(Realm realm) {
       this.realm = realm;  
    public Foo getFooById(String fooId) {
        Foo foo = realm
        return realm.copyFromRealm(foo);
    public void save(Foo detachedObjectToSave) {
       // isValid() always returns false on detached objects.
       if (object.isValid()) { 
          throw new IllegalArgumentException("received realm object is not a detached object");

       // please note that this also could be saved 
       // in background using Realms asynchronous transactions.