Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use case example for copyToRealm() in Realm

Tags:

realm

Could someone give a simple use case example why someone would use copyToRealm() instead of createObject() ?

It is not clear to me why and when would anyone use copyToRealm() if there is createObject().

In the example here they seem pretty much the same https://realm.io/docs/java/latest/ .

copyToRealm() takes an unmanaged object and connects it to a Realm, while createObject() creates an object directly in a Realm.

like image 911
jhegedus Avatar asked Jan 05 '23 15:01

jhegedus


2 Answers

For example it is very useful when you copy objects generated by GSON - returned from your Rest API into Realm.

like image 67
Divers Avatar answered Feb 03 '23 08:02

Divers


realm.createObject() also returns a RealmProxy instance and is manipulated directly and therefore creates N objects to store N objects, however you can use the following pattern to use only 1 instance of object to store N objects:

    RealmUtils.executeInTransaction(realm -> {
        Cat defaultCat = new Cat(); // unmanaged realm object

        for(CatBO catBO : catsBO.getCats()) {
            defaultCat.setId(catBO.getId());
            defaultCat.setSourceUrl(catBO.getSourceUrl());
            defaultCat.setUrl(catBO.getUrl());
            realm.insertOrUpdate(defaultCat);
        }
    });

But to actually answer your question, copyToRealmOrUpdate() makes sense if you want to persist elements, put them in a RealmList<T> and set that RealmList of newly managed objects in another RealmObject. It happens mostly if your RealmObject classes and the downloaded parsed objects match.

@JsonObject
public class Cat extends RealmObject {
    @PrimaryKey
    @JsonField(name="id")
    String id;

    @JsonField(name="source_url")
    String sourceUrl;

    @JsonField(name="url")
    String url;

    // getters, setters;
}

final List<Cat> cats = //get from LoganSquare;
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Person person = realm.where(Person.class).equalTo("id", id).findFirst();
        RealmList<Cat> realmCats = new RealmList<>();
        for(Cat cat : realm.copyToRealmOrUpdate(cats)) {
             realmCats.add(cat);
        }
        person.setCats(realmCats);
    }
});
like image 38
EpicPandaForce Avatar answered Feb 03 '23 07:02

EpicPandaForce