0

Everytime I load my list of items I realized that the child_added event is called, but why? Wasn't this event supposed to be called only when a new child is added to the database?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
flpn
  • 1,868
  • 2
  • 19
  • 31

3 Answers3

2

A child added listener will always be invoked for all existing children under a node when the listener is first added. Then as new children are added, the listener will continue to get invoked. This is the expected behavior. It allows your code to stay in sync with the entire contents of that node at all time.

If you want to listen to only children that are recently added, you will have to come up with a query that involves looking at a timestamp field in each child to figure out if it's of interest to your code.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
2

From https://firebase.google.com/docs/database/admin/retrieve-data#child-added

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

To get around it, there are already several posts that answer that:

Joseph Webber
  • 2,010
  • 1
  • 19
  • 38
1

Because (in my opinion) it is handy way of populating lists, you can use only add or delete events and stop using load as such.

Suppose you have list of something in ios or android. What you need is:

  • load it some time at the beginning - you can use add event, firebase will call it so many times as the number of items in node (list);
  • react on adding new items from another device - again, add event will be called and you will populate the new item into your list;
  • delete (same as add).
Cynichniy Bandera
  • 5,991
  • 2
  • 29
  • 33