2

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.

#askFirebase 

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using addListenerForSingleValueEvent() to retrieve data only once. However, at the same time I have persistence enabled setPersistenceEnabled(true). So, this always causes single value event to bring me data from my local cache. Is there a way to avoid this and force single value event to get data from remote (Firebase itself) while persistence is enabled?
@UgurcanYildirim No, you cannot change this behaviour. When you are adding a listener, it means that you are listening for database changes. In case you are using addListenerForSingleValueEvent(), it means that you geeting the initial data once and then you also get every new change. So the onDataChange() is triggered on every change. So there is no need to get data from Firebase server since there is nothing new. You get the data from the server only when something new appears, right?