Search code examples
androidrealm

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?


Solution

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