0

Thanks in advance.

I have scenario where i wanted to check the data difference between existing and new realm model object.

Example

public class PostModel extends RealmObject {

    @Required
    @PrimaryKey
    @Index
    private String postId;
    private String message;

}

Let say we have two objects

Old

PostModel old = new PostModel("one", "Welcome");
realm.copyToRealm(old);

New Object

PostModel newOne = new PostModel("one", "Welcome to World");

before updating the old object with newOne should check data change, if change is there then should insert in the realm, like below

realm.dirtyCheckAndUpdate(old, newOne);

//underlying it should do below

  1. Getting the record with id "one"
  2. Check the difference between db record and new record (!old.message.equalsIgnore(newOne.message)).
  3. if change is there then copyToRealmOrUpdate() should happen.

I just gave an example, i need to to this for complex RealmModel with relationship.

Suresh
  • 1,199
  • 2
  • 12
  • 36

1 Answers1

0

Why do you need to check? You can just call copyToRealmOrUpdate()? It will update data regardless, but if it overrides the data with the same data the end result is the same.

Otherwise, you will be forced to implement all the checking yourself, which is time-consuming and error-prone. You could also make your own annotation processor that generated the logic for you. It would look something like:

public boolean compare(PostModel m1, PostModel m2) {
  if (!m1.getId().equals(m2.getId()) return false;
  if (!m1.getMessage().equals(m2.getMessage()) return false;
  if (!PostModelReference.compare(m1.getRef(), m2.getRef()) return false; // Recursive checks
}
Christian Melchior
  • 19,978
  • 5
  • 62
  • 53