Reputation: 1192
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 callback would I have to use such that it is only triggered for the 5 new items that have been added?
I have offline persistence enabled on my client with Firebase.getDefaultConfig().setPersistenceEnabled(true);
. I have a listener bound to an activity listening for children added to a reference. 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? Or if that's not possible, then to trigger only those onChild*
callbacks after the most recent update from firebase?
Upvotes: 7
Views: 6060
Reputation: 598847
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)...
Upvotes: 13
Reputation: 2362
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.
Upvotes: 1