Firebase onChildAdded for new data

前端 未结 2 1830
刺人心
刺人心 2020-12-11 04:37

If I have a list of 50,000 items stored in my firebase reference, and 5 items have been added to that list since the last time the client was online and listening, which cal

相关标签:
2条回答
  • 2020-12-11 04:56

    Everytime the activity is created onChildAdded is called for all the data in the reference. Is it possible to make onChildAdded and onChildRemoved be called only for "diff" between my local cache and the data on the firebase server?

    No, this is not possible. From the documentation on event types:

    child_added is triggered once for each existing child and then again every time a new child is added to the specified path

    Now back to your initial question:

    which callback would I have to use such that it is only triggered for the 5 new items that have been added?

    That would be:

    ref.limitToLast(5)...
    

    But this requires that you know how many items were added to the list, since you last listened.

    The more usual solution is to keep track of the last item you've already seen and then use startAt() to start firing events from where you last were:

    ref.orderByKey().startAt("-Ksakjhds32139")...
    

    You'd then keep the last key you've seen in shared preferences.

    Similarly you can keep the last time the activity was visible with:

    long lastActive = new Date().getTime();
    

    Then add a timestamp with Firebase.ServerValue.TIMESTAMP to each item and then:

    ref.orderByChild("timetstamp").startAt(lastActive+1)...
    
    0 讨论(0)
  • 2020-12-11 04:57

    You should use on('child_changed'). Normally, on() is used to listen for data changes at a particular location. However, on('child_changed') notifies you

    when the data stored in a child (or any of its descendants) changes.

    It will pass a data snapshot to the callback that contains the new child contents. Keep in mind that a single child_changed event may potentially represent multiple changes to the child.

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