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.
For example it is very useful when you copy objects generated by GSON - returned from your Rest API into Realm.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With