Dominic Dominic - 1 year ago 211
Android Question

Firebase Realtime Database addValueEventListener

I have set setPersistenceEnabled to true and I am using a addValueEventListener and inside that a onDataChange method.
Will my app always download the data from server every time that method is called or will my app get the data from the cache if available?
When I am offline I am sure that the data comes from the cache.


Answer Source

When you attach a listener with addValueEventListener() and the data is available in the local disk cache, the onDataChange() method will immediately fire with the data from the cache.

The Firebase client will then register with the server for updates to the data. Any time it receives updated data, it will invoke onDataChange() again.

So if you have stale data in your local disk cache, you may receive two calls to onDataChange() in "quick" succession: one with the stale data and the second one with the latest data. There is currently no way to see whether the data is stale or not.

The only time when this really creates a tricky situation is when you use addListenerForSingleValueEvent(). Since you will only get the first onDataChange() event there, you may only get the stale data. This is one of the reasons that we recommend not to mix disk persistence with single-value event listeners.