Anjani Anjani - 1 year ago 70
Android Question

Practical use of @Ignore in Realm?

I've been trying to add Realm in my Android app. Their docs are pretty well explained & easy to follow. But it fails to explain this one particular area. I'm unable to figure out the practical use for the

annotation. I know that fields under this annotation are not persisted.

Can someone please share a few use cases. Also I wanted to know the scope of such fields. I mean, if I set an
field to some value, would that value be available to the other classes in my app for that particular launch session. If yes, then how do we access it? If no (which I guess is the case), then why do we need such a field anyway?

I've searched here and on web but couldn't find the relevant information. If out of my ignorance, I've missed upon some resource, please guide me to it.


Answer Source

Accordingly to the official documentation (see @Ignore is useful in two cases:

  1. When you use GSON integration and your JSON contains more data than you want to store, but you still would like to parse it, and use right after.

  2. You can't create custom getters and setter in classes extending RealmObject, since they are going to be overridden. But in case you want to have some custom logic anyway, ignored fields can be used as a hack to do that, because Realm doesn't override their getter & setters. Example:

    package io.realm.entities;
    import io.realm.RealmObject;
    import io.realm.annotations.Ignore;
    public class StringOnly extends RealmObject {
        private String name;
        private String kingName;
        // custom setter
        public void setKingName(String kingName) { setName("King " + kingName); }
        // custom getter
        public String getKingName() { return getName(); }
        // setter and getter for 'name'

Ignored fields are accessible only from the object they were set in (same as with regular objects in Java).