Home > front end >  Is there a way to check if the ValueEventListener removed successfully?
Is there a way to check if the ValueEventListener removed successfully?

Time:10-03

I'm working on an Android application wherein I wanna check for changes in Firebase Database. However, I just wanna listen for changes in the database up till 5 changes are made. After that, I wanna close the valueEventListener.

valueEventListener = databaseReference.child(roomID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if(i == 5){
                Log.d(TAG,"REMOVING");
                databaseReference.removeEventListener(valueEventListener);
            }else{
                Log.d(TAG,"CALLED");
            }
            i  ;
        }

So after this, I go to Firebase and manually change the values. For the first five changes made, "CALLED" is printed in logs 5 times, and for the 6th change "REMOVING" is printed. So I suppose it won't print anymore for changes made further. But even after that, as I change the values in firebase it keeps printing "CALLED" in logs. So I'm confused, did the connection close, or is it still open and listening to changes?

CodePudding user response:

You are removing the listener from the wrong reference. To solve this, please change:

databaseReference.removeEventListener(valueEventListener);

To:

databaseReference.child(roomID).removeEventListener(valueEventListener);
//                 ^ ^ ^ ^ ^ ^

Even if you remove the listener correctly, "REMOVING" will be printed out once, since you detach the listener after that log statement.

  • Related