Frequently I see code snippets like this:
public RealmResults<MyObject> getMyObjects(List<Integer> ids) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
RealmQuery<MyObject> query = realm.where(MyObject.class);
for (int i=0; i< ids.size(); i++) {
query = query.equalTo("id", ids.get(i));
if (i != ids.size() -1) {
query = query.or();
}
}
return query.findAll();
} finally {
if (realm != null) realm.close();
}
}
Is it really necessary to reassign the output of a query operator to the RealmQuery object? Will this other snippet achieve the same result? (hint: i have removed query =
before the calls to .equalTo()
and .or()
)
public RealmResults<MyObject> getMyObjects(List<Integer> ids) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
RealmQuery<MyObject> query = realm.where(MyObject.class);
for (int i=0; i< ids.size(); i++) {
query.equalTo("id", ids.get(i));
if (i != ids.size() -1) {
query.or();
}
}
return query.findAll();
} finally {
if (realm != null) realm.close();
}
}
The query essentially functions like a builder, so in reality, the returned builder has its state set with the given condition. This means that the assignment is optional.
This is why queries like the structure of the one below work:
query.equalTo(...).equalTo(...).beginGroup()....endGroup().findAll()
The returned parameter is this
and not a new RealmQuery.