SonVi
SonVi

Reputation: 91

How to return value when Realm transaction success?

I have this method, i want return value when the transaction complete, but i cant. This's my code

public List<Group> getConversations() {

        final RealmResults<Group> conversations;

        try {

            mRealm = Realm.getDefaultInstance();
            mRealm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    RealmResults<Group> conversations = realm.where(Group.class).findAllSorted("time", Sort.DESCENDING);
                    cursorConversation(conversations);
                }
            }, new Realm.Transaction.OnSuccess() {
                @Override
                public void onSuccess() {
                   //return conversation
                }
            });
        }

return null;

    }

What should i do ?

Upvotes: 1

Views: 1039

Answers (2)

Aks4125
Aks4125

Reputation: 5720

I am not sure what are you doing in cursorConversation(..) but you can use the same method on returned values from Realm.

give a try

public List<Group> getConversations() {

    try (Realm realm = Realm.getDefaultInstance()) {

        return realm.copyFromRealm(realm.where(Group.class).findAllSorted("time", Sort.DESCENDING));
    }

}

Upvotes: 1

Amit Barjatya
Amit Barjatya

Reputation: 259

You don't need to run a transaction for getting the conversations. You can run your query on the realm db and add a change listener to the result. When the query completes, it'll call that change listener with the RealmResults<Converstaion>, Check this link for more.

Something like

public void listenToConversations(RealmChangeListener<RealmResults<Conversation>> listener) {
     RealmResults<Conversations> conversations = realm.where(Group.class).sort("time", Sort.DESCENDING).findAllAsync();
     conversations.addChangeListener(listener);
}

where listener is something like

listener = new RealmChangeListener<RealmResults<Conversations>>() {
           \@Override
           public void onChange(RealmResults<Conversations> conversations) {
               // React to change
           }
       }

You'll also need to remove listener to avoid any memory leaks.

Upvotes: 0

Related Questions