在 RealmObject 之外创建托管 RealmList

Creating managed RealmList outside RealmObject

在我的应用程序中,我有一个方法接受 ArrayList 个 ID 和 returns 个 RealmList 个属于这些 ID 的机器。

public RealmList<Machine> getMachinesById(ArrayList<Long> machineIds) {
    RealmList<Machine> machines = new RealmList<Machine>();
    for (int i = 0; i < machineIds.size(); i++){
        Machine m = getMachineById(machineIds.get(i));
        if (m != null) {
            machines.add(m);
        }
    }
    return machines;
}

getMachineById() 函数只是为特定的 id 找到正确的机器。

我想进一步过滤此输出,但是,当我尝试通过 .where() 获取 RealmQuery 时,出现异常告诉我应该将此 RealmList在 'managed mode'。

Caused by: io.realm.exceptions.RealmException: This method is only available in managed mode
                                                 at io.realm.RealmList.where(RealmList.java:425)

我知道我收到此错误是因为此列表是独立的,不受 Realm 管理。

可能很重要的一点是,此函数将被调用很多次,因为每次刷新我的应用程序中的某些列表时都会触发它。这意味着(如果可能的话)每次我创建一个新的托管 RealmList 时。

我的问题:

Is there any way to let this RealmList be managed by Realm?

是的。有。但是 RealmList 的意义在于它应该是 RealmObjects 的字段。例如:

public class Factory {
    RealmList<Machine> machineList;
    // setter & getters
}

Factory factory = new Factory();
RealmList<Machine> machineList = new RealmList<>();
// Add something to the list
factory.setMachines(machineList);
realm.beginTransaction();
Factory managedFactory = realm.copyToRealmOrUpdate(factory);
realm.commitTransaction();

Managed表示已经持久化Realm。

If this is possible, is it a problem that this function is being called pretty often

视情况而定,如果您不需要再次持久化它们,请参阅答案 3。

Is there any other (preferred) way to achieve this (List of IDs > RealmResults/RealmQuery)

在您的情况下,也许您可​​以改用 ReaulResults?例如:

RealmQuery<Machine> query = realm.where(Machine.class);
for (int i = 0; i < machineIds.size(); i++){
    if (i != 0) query = query.or();
    query = query.equalTo("id", machineIds.get(i));
}
RealmResults<Machine> machines = query.findAll();