0

I am using Firebase. My problem is, while i'm querying objects and then modifying them, my main ui thread goes ahead and runs the next methods. I want my main ui thread to wait until my firebase query is finished and I made all the necessary changes in onDataChange AND THEN continue to run my other functions i written.

Currently, I just imported the external library "Otto" but im not sure how to use it and I was hoping someone can help guide me.

                Firebase cardReference = mRef.child("reference");
                cardReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                    //DO STUFF
                    }
                    @Override
                    public void onCancelled(FirebaseError firebaseError) {

                    }
                });
               //Once STUFF is done, run nextMethod()
               nextMethod();
        }
TheQ
  • 1,949
  • 10
  • 38
  • 63
  • Why dont you use `nextMethod()`in `onDataChange ` after editing stuff?`Otto` is pub-sub for operations. – adnbsr Nov 20 '16 at 01:14

1 Answers1

0

Firebase reads the data from the database asynchronously. There is no way to make your app wait, without showing an "Application Not Responding" to your users.

Instead you need to reframe your logic. Instead of saying "first load the reference, then do the next method", change it to "start loading the reference, when that is done do the next method". In code that translates to:

Firebase cardReference = mRef.child("reference");
cardReference.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Whenever STUFF is done, run nextMethod()
        nextMethod();
    }
    public void onCancelled(FirebaseError firebaseError) {
        throw firebaseError.toException();
    }
});

The added advantage of this approach is that nextMethod() will now also be called whenever the reference data changes. Updating your UI in such a case is one of the special effects that your users will appreciate once they notice.

For some more information, also read these:

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807