Ridcully
Ridcully

Reputation: 23655

Fetching nested objects in Realm is slow

I have two RealmObject classes, NodeToUser and Task:

class NodeToUser extends RealmObject {
    int id;
    Task task;
    String otherStuff;
}

class Task extends RealmObject {
    int id;
    String name;
}

Now, I want all Tasks, where NodeToUser.otherStuff == "foo".

All I came up with, is doing a Query on NodeToUser like so:

RealmResults<NodeToUser> nodes = realm.where(NodeToUser.class)
    .equalTo("otherStuff", "foo")
    .findAll();

And then go over the result and collect the actual Tasks.

List<Task> tasks = new ArrayList<>();
for (NodeToUser n : nodes) tasks.add(n.getTask());

However, this iterating over the result and collecting the objects I really want, is very slow -- just a rough value: for 100 NodeToUser objects it takes 2 seconds on my device.

Question: Is there a better/faster way, or some way to create the query so that I can get the list of tasks directly?

Upvotes: 0

Views: 197

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

class NodeToUser extends RealmObject {
    int id;
    Task task;
    String otherStuff;
}

class Task extends RealmObject {
    int id;
    String name;

    @LinkingObjects("task")
    private final RealmResults<NodeToUser> fromNodes = null;
}

then

RealmResults<Task> tasks = realm.where(Task.class)
        .equalTo("fromNodes.otherStuff", "foo")
        .findAll();

Upvotes: 1

Related Questions