I have a list of chat rooms for a given user at one location, and total number of messages for a given chat room at another location. I want to keep track of a number of messages at chatrooms user belongs to.
I have a following snippet:
//getting all chat rooms this user belongs to
mFirebase.child("myChatRooms").child("testUser").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded (DataSnapshot dataSnapshot, String previousKey){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
ChatRoom myRoom = postSnapshot.getValue(ChatRoom.class);
//listening to message count in every chat room user belongs to
mFirebase.child("chatRoomMessageCount").child(postSnapshot.getKey()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//number of messages have changed
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
//......
}
The question is, how do I remove all those ValueEventListener's later, when onChildRemoved will be called, or I won't need them anymore?
What is the recommended approach in dealing with this situation? Should I store child key and listener in HashMap and keep track of them myself or there is some way to remove all listeners for a given firebase location?