1
votes

TL;DR: we are looking for a pattern of implementing "versioned" objects in Realm, so the "last" version is accessible fast (just by primary key), and creating a "historical" version from "last" version before updating is easy, as well as accessing all old versions of the object.

Some background.

We are implementing Realm as a replacement for SQLite in Android app and also "from scratch" in iOS app. We have a unified backend for both apps and want to keep the Realm object representation as close as possible between platforms.

In SQLite, we have 2 tables with basically the same structure, one having the last version of each object, and the second - all previous versions. Before updating the "main" table, we copy the row-to-be-updated to the "history" table and then do the update.

1
Sounds like something that might be possible using Realm Functions. Have you taken a look there yet? - Avi Warner
@AviWarner these are realm object server features, we are not using them. - saabeilin

1 Answers

0
votes

Welp, the only option I can think of is to

have 2 tables with basically the same structure, one having the last version of each object, and the second - all previous versions.

The key difference would be that the history table has no primary key (or it is constructed from concating original primary key with version number).

public class Dog extends RealmObject {
    @PrimaryKey
    private String dogId;

    @Index
    private String dogName;

    private int version;
}

public class DogHistory extends RealmObject {
    private String dogId; // decide if primary key from dogId+version is needed

    @Index
    private String dogName;

    private int version;
}

And then map them over.

DogHistory dogHistory = new DogHistory(); 
dogHistory.setDogId(currentDog.getDogId());
dogHistory.setDogName(currentDog.getDogName());
dogHistory.setVersion(currentDog.getVersion());
realm.insert(dogHistory); //not "insertOrUpdate" if no PK field

The tricky thing is that you'd only be able to see them as "the same object" if you expose the getters/setters via interface. Or you map them back to Dog, but it will become an unmanaged instance then.