once("value") vs. on("child_added") vs. child().once("value")

3,445 views
Skip to first unread message

Benny Lichtner

unread,
Dec 5, 2012, 8:50:00 PM12/5/12
to fireba...@googlegroups.com
Say I have a tree like:

myTree: { a: alligator, b: breadcrumb, c: coconut, d: doughnut, e: elephantnut }

and I want to fetch children a, c, and e. I see at least three ways to fetch the data: myTree.once("value"), myTree.on("child_added"), and myTree.child("a").once("value"), etc.

My intuition is that the first method is the best if you don't care about loading the whole tree into memory, the second is not so good because you'd need to call myTree.off if you only wanted to read the data once, and the third is maybe a little slower than the first but allows you to fetch only the children that you want. Is this correct? Does it ever really matter?

--Benny

Anant Narayanan

unread,
Dec 5, 2012, 9:09:26 PM12/5/12
to fireba...@googlegroups.com
Hi Benny,

Great question! Your analysis seems correct.

In the end, I think the answer depends on what you are optimizing for. If the goal is to fetch as little data as possible from the network, then I'd recommend myTree.child("a").on("value") - and so on for each child you are interested in. You should use .once() only if you are sure that you won't need updates in the future, because if you end up calling .once() a bunch of times, that could get pretty inefficient (and one of Firebase's salient features is the ability to get real-time updates!).

On the other hand, if you anticipate needing child "b" sometime later in the code, it's probably better to fetch the whole tree with myTree.on("value") - the same comment about .once() applies.

The second approach would only be needed if you also need to know when a new child is added, which may or may not be the case in your application. You might also consider using .on("child_changed") if you know that there will be a fixed number of children, but want to receive a callback if their values change.

Feel free to give us more details about your specific use case, and we'd be happy to recommend alternatives!

Cheers,
-Anant



--Benny

--
You received this message because you are subscribed to the Google Groups "Firebase Google Group" group.
To post to this group, send email to fireba...@googlegroups.com.
 
 

Benny Lichtner

unread,
Dec 5, 2012, 9:37:40 PM12/5/12
to fireba...@googlegroups.com
Thanks, Anant! This is perfect.

--Benny
Reply all
Reply to author
Forward
0 new messages