从领域分离 RealmObject / 将托管 RealmObject 转换为非托管对象

Detach RealmObject from Realm / Convert managed RealmObject to unmanaged Object

我想从它的 Realm 中 "detach" 一个 RealmObject,这意味着我希望能够从一个方法中 return 一个 RealmObject 并且在 close Realm 实例后可以使用它。

像这样:

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

目前 getPersonWithId(mContext, personId).getName() 会 return 一个错误,如预期的那样。

拥有托管对象也意味着该对象是不可变的(无法修改),因此任何更新对象的方法如 person.setName(String name) 都将失败,因为该对象是托管对象。

我希望有一个像Person person = person.detachFromRealm();

这样的方法

有人知道 solution/workaround 这个问题吗?

有此 here 的功能请求。对此没有真正好的解决方案,只有解决方法。

解决方法 是手动将数据从一个对象复制到另一个对象。我的 RealmObjects 有大量字段,因此手动将属性从一个对象复制到另一个对象是不行的。

我决定将 MapStruct. Here's a sandbox 项目与 RealmMapStruct 一起使用,而不是手动编写 "copying code"。它似乎工作得很好,至少对于简单的模型是这样。

Android 领域现在支持附加和分离领域对象。所以你可以这样做:

RealmObject objectCopy = realm.copyFromRealm(RealmObject object);

以下是文档中的详细信息:

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