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?
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()
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.
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