Firebase onChildAdded for new data

前端 未结 2 1835
刺人心
刺人心 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)...
    

提交回复
热议问题