What is the difference between ChildEventListener and ValueEventListener Firebase interfaces?

后端 未结 3 683
悲&欢浪女
悲&欢浪女 2021-01-01 18:22

The documentation says they both listen to changes at a Firebase database location.

相关标签:
3条回答
  • 2021-01-01 18:36

    They do almost same thing, though ChildEventListener can be sometimes more flexible: with ChildEventListener you can specify different behavior for 4 actions (onChildAdded, onChildChanged, onChildMoved and onChildRemoved), while ValueEventListener provides only onDataChanged.

    Also ChildEventListener provides DataSnapshots (immutable copies of the data) at child's location while ValueEventListener provides a DataSnapshot of a whole node.

    0 讨论(0)
  • 2021-01-01 18:57

    ValueEventListener gets fired only when that specific value changes, but ChildEventListener listens not only value of that node, but also for all child nodes of tree. Say, you have node, which has one children. ValueEventListener will be triggered when this node changes, but ChildEventListener will also be triggered whenewer child values is changed as well. Documentation says, that you should use ChildEventListener with caution - it can be triggered a lot of times.

    0 讨论(0)
  • 2021-01-01 19:00

    these are the key differences between the two

    if your database has following records:

      -LDU4T1buanVuJrpOYxW
          message:"hi stack"
          user: "john"
      -LDasdfa1buanVuJrpOYxW
          message:"hi john"
          user: "stack"
    

    1) on new entry:

    • a)ChildEventListener.onChildAdded will be called once but the datasnapshot will only have the one added
    • b) ValueEventListener.onDatachange will be called once but the datasnapshot will have everybody

    2) because of a) getting the new record in childeventlistener is

     public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Map<String,String> map =(Map) dataSnapshot.getValue();
        String message = map.get("message").toString();
    

    because of b) getting the new record in ValueEventListener is

        public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                   .... loop until end
                    Map<String,String> map = (Map)data.getValue();
                    String message = map.get("message").toString();
    

    so for example if you don't care what happen when somebody delete the first in ValueEventListener you always get notified but in ChildEventListener you only get notified if you override onChildRemoved.

    so it depends on what you want to do. for example in a chat app. you will only care about new messages, you don't want to be reinserting all messages again in your chat room.

    0 讨论(0)
提交回复
热议问题