Ninja420
Ninja420

Reputation: 3872

Firebase Caching : Does Firebase cache query results or maintain an offline database?

Firebase caching is still a mystery to me.

I am querying same real time database by two different methods. The database has persistence enabled

Imagine there are 6 entries 1, 2, 3, 4, 5, 6

  1. A single value listener to fetch last 5 entries (always returns from cache since persistence is enabled) [ 2, 3, 4, 5, 6 ]
FirebaseDatabase.getInstance().getReference(path).query.orderByKey().limitToLast(count)
  1. Another value listener to fetch value after the last fetched query (returns the latest value) if 7 gets added to the above list it will return 7

But when second time I run the first query again it returns the same value [2, 3, 4, 5, 6] while it should return 3-7 if firebase was caching value instead of query results.

Upvotes: 0

Views: 1243

Answers (1)

Kato
Kato

Reputation: 40582

Firebase Realtime Database and Firestore both cache data locally. The nuances of how and when data is downloaded vary, but essentially adhere to this simplified model in Realtime Database:

  • The first time a listener is registered on a new path data is downloaded from the server. Note that if several listeners are on the same child tree, they only get downloaded once (e.g. /foo and /foo/bar only perform one download as /foo/bar can re-use /foo's data) not count as they just use the data from their parent),
  • From then forward, the client sends a hash representing its current data to the server, and only receives deltas (changed records).
  • This only applies when using on() and not for once() operations.
  • If you enable offline persistence, you will have a locally cached copy of the data even if the app starts in offline mode. However, when the app goes online, it still requires an initial download of the data and does not use a delta.

Firestore works a bit differently and I'm not sure on the nuances, but I'll try to get those documented here as well for reference.

Upvotes: 2

Related Questions