0

In my angular app, I use AngularFire to access firebase realtime database.

I have following method to retrieve entities in a certain database path.

private db: AngularFireDatabase;

public getAll(): Observable<Item[]> {
    return this.db.list<Item>('some/db/path').valueChanges();
}

If I call above method multiple times, does the data get downloaded multiple times from server, or firebase client uses a local cache second time onward?

If data gets downloaded multiple times, is there any way I can instruct firebase client to use local caching?

Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179

1 Answers1

1

The Firebase Realtime Database client deduplicates listeners. That means that:

this.db.list<Item>('some/db/path').valueChanges();
this.db.list<Item>('some/db/path').valueChanges();

The above code will only download the data once initially, and only download the delta once for each change.

Note that you can check this for yourself by looking at the Web Socket traffic in the network panel of your browser.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for the answer. Not directly related to this, but I have another doubt. If I have persistence enabled in an android client, if the data of a certain db path is already cached, When the android app is restarted, if I subscribe for value changes of that path, will firebase download all data of that path again, or will it only download the diff between the cache and the server? – Lahiru Chandima Sep 04 '18 at 14:59
  • 1
    It does a so-called delta-sync in that case. This means it calculates the hashes of data it has cached, and sends those to the server. The server then only sends data that was modified back. This approach is not guaranteed to be minimal (that would mean the client would have to send a hash of each value), but is typically a lot smaller than sending all data. – Frank van Puffelen Sep 04 '18 at 15:06
  • Good to hear that. Also, I read in several places that if I use `keepSynced()` for a certain path in an android client, firebase will download all data of that path in each app restart. But, according to this mechanism you described, there shouldn't be any need to do so. Am I correct? – Lahiru Chandima Sep 04 '18 at 15:14
  • Correct. You can check the [debug logs](https://firebase.google.com/docs/reference/android/com/google/firebase/database/FirebaseDatabase.html#setLogLevel(com.google.firebase.database.Logger.Level)) to see what actually happens on the wire. Especially the hashing is quite education, although a bit hard to follow. – Frank van Puffelen Sep 04 '18 at 16:54