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:
- Is this expected behavior?
- If so, why is it happening?
- Is there a way to avoid three calls to onDataChange?
Thanks a lot in advance