LeaningAndroid
LeaningAndroid

Reputation: 475

onDataChange is getting called more than once when offline is enabled in firebase

I have been struggling with this for over half a day and eventually thought to pose my question here.

I am using firebase realtime database developing an Android application. I have turned on offline perssistance.

I am creating a new ValueEventListener object with an onDataChange method as below:

changeListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
...}};
dbRef.addValueEventListener(changeListener);

Through another fragment in the app, I remove an element from where dbRef is pointing to. Let's assume initially I had ten elements in dbRef. If I put a break point in the onDataChange code, I see that it gets called three times consecutively. First time around, dataSnapShot has nine elements in it. The second time, it has ten elements in it (including the one that was just removed), and finally the third time, it has again nine elements it.

Please note, if I turn off offline persistence, this issue would not happen. Neither it will happen, if I manually remove an element from the database consul. In both cases, onDataChange gets called only once.

I also properly add the listener in onResume method in my fragment and remove it in my onPause.

My questions are:

  1. Is this expected behavior?
  2. If so, why is it happening?
  3. Is there a way to avoid three calls to onDataChange?

Thanks a lot in advance

Upvotes: 1

Views: 149

Answers (1)

LeaningAndroid
LeaningAndroid

Reputation: 475

I found a decent way to tackle this.

In the fragment in which I am removing the element in dbRef, instead of removing the element and immediately getting back to this fragment (that contains the valueEventlistener), I add a success listener as below:

dbRef.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    getFragmentManager().popBackStackImmediate();
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception exception) {

                                }
                            });

now, onDataChange gets called only once. Thinking about it, this makes a lot of sense. You don't want to remove an item from the Database and immediately process the data. Instead, you want to wait until you make sure the removal took affect, before further processing.

Upvotes: 1

Related Questions