Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

java - How to keep track of listeners in Firebase on Android?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...