Search code examples
androidrealm

Get RealmObject attribute asynchronously


I have a conversation RealmObject which contains a RealmList of messages (My messages don't know about the conversations). I want to query and sort them asynchronously.
Here is my awful attempt but I post it to give you a better idea of ​what I want to do :

return realm.where(Conversation.class)
            .equalTo("id",conversationId)
            .findFirstAsync()
            .getMessages().sort("receivedDate", Sort.DESCENDING)
            .asFlowable();

It doesn't work and this exception has been thrown:

java.lang.IllegalStateException: The pending query has not been executed

Currently I have no idea how to query them asynchronously and get back them in the UI thread without changing my schema.

Edit:
My schema is very simple :

public class Message extends RealmObject{
private String content;
private Date receivedDate;
}

public class Conversation extends RealmObject{
    private String id;
    private RealmList<Message> messages;
}

Solution

  • Without seeing your schema so I can't know if this is possible with linking objects, I guess I'd try the following

    return realm.where(Conversation.class)
            .equalTo("id",conversationId)
            .findFirstAsync()  // maybe use findAllAsync instead? 
            .asFlowable()
            .filter(RealmResults::isLoaded)
            .switchMap(conversation -> 
                  conversation.getMessages().where().findAllSortedAsync("receivedDate", Sort.DESCENDING)
                    .asFlowable()
                    .filter(RealmResults::isLoaded));
    

    If the object can be deleted, then you might want to switch over to findAll* or check against isValid as well.