Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detach RealmObject from Realm / Convert managed RealmObject to unmanaged Object

Tags:

android

realm

I want to "detach" a RealmObject from its Realm, meaning that I want to be able to return a RealmObject from a method and be able to use it after I close the Realm instance.

Something like this:

public Person getPersonWithId(final Context context, final String personId){
    Realm realm = Realm.getInstance(context);
    Person person = realm.where.....;
    realm.close();
    return person;
}

Currently getPersonWithId(mContext, personId).getName() will return an error, as expected.

Having a managed object will also mean the object is immutable (cannot be modified) and so any method updating the object like person.setName(String name) will fail due to the object being a managed object.

I wish there would be a method like Person person = person.detachFromRealm();

Does anyone know a solution/workaround for this problem?

like image 393
Tudor Luca Avatar asked Aug 27 '15 17:08

Tudor Luca


2 Answers

Android realm now supports attaching and detaching realm object. So you can do like this:

RealmObject objectCopy = realm.copyFromRealm(RealmObject object);

Here are details from the documentation:

Instances of Realm objects can be either managed or unmanaged.

Managed objects are persisted in Realm, are always up to date and thread confined. They are generally more lightweight than the unmanaged version as they take up less space on the Java heap.

Unmanaged objects are just like ordinary Java objects, they are not persisted and they will not be updated automatically. They can be moved freely across threads.

It is possible to convert between the two states using Realm.copyToRealm() and Realm.copyFromRealm()

like image 192
Semyon Avatar answered Oct 12 '22 13:10

Semyon


There is a feature request for this here. There is no real great solution for this, only workarounds.

A workaround is to manually copy the data from one object to another. My RealmObjects have tons of fields so manually copying the properties from one object to another one is a NO GO.

Instead of manually writing "copying code" I decided to use MapStruct. Here's a sandbox project with Realm and MapStruct. It seems to work just fine, at least for simple models.

like image 25
Tudor Luca Avatar answered Oct 12 '22 13:10

Tudor Luca