When I first started using Firebase, it seemed most straightforward to use on('child_added'...) and in the callback, grab the data and stuff it somewhere. Then at some point it became clear I could use once('value'...) callbacks to always traverse Firebase's local copy, and never copy any data out of on() callbacks. On() callbacks in this scenario could serve only as event notification, not data delivery. Ever since starting to think this way, I've been waffling on whether to rely completely on once() for reading memory, or not.
I'm curious if there are opinions, or better yet accrued wisdom & evidence, for or against sticking to using once() for re-reading data from memory, versus copying the data locally to a separate structure in memory, and what the pros and cons are - specifically if there might be better practice here or large advantages or disadvantages that I'm not considering.
In my case, I want to be able to re-play a lot of data, and very often, and I want it to re-play very quickly, on the same order as if I were reading my own local copy, and without stalling for any reason. Is it reasonable to ask this much of once(), assuming the ref has already been synced at least once? Here are the main issues that I can see with using once() like this. Am I right, and are there others?
Pros of using once() for re-reading local data:
- Completely avoids the problem of trying to keep a local copy and remote copy in sync.
- Less code, easier development.
- Firebase has a copy of the data. If I copy it in on() callbacks, I have 2 copies, and I'm wasting a bunch of memory.
Cons of using once() for re-reading local data:
- Somewhat binds the code to the Firebase schema. Could make it harder to incorporate local storage, or to use or migrate to or from other remote databases.
- I'm not sure about the performance of once(). Its relatively fast, but is getting the value of a snapshot a lightweight o(1) wrapper around returning something already sitting in memory? Or is it doing a deep-copy or something else o(n) that also duplicates memory and I have to pay for the copying every time I read memory, instead of only once if I copy in an on() callback? And in either case, is once() going to stay at least that fast, or could it in the future result in additional transfer of data, e.g., from data that was pushed out of a local cache?
- Getting the data I need using once() can be a little taxing. Its slightly heavier to code every time I need to access something. And since the callback is async, it sometimes means a larger refactoring of an algorithm to get all the code in one place (inside the callback). Reading from multiple refs simultaneously means nested once() callbacks. Incidentally, I have been imagining a helper function, at least in javascript, that does un-currying of nested once() callbacks, e.g., a single callback that gets all the snapshot values from a list of refs. Has anyone done something like that?
--
David.