Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to only download data from Firebase if the cached data is outdated?

My first big app with Firebase just launched and I'm running into a problem - I am quickly running out of download bandwidth.

I have looked into a couple of options to cache data. I want the cached data to be used only if it is current. If the data has been updated on Firebase since the cache was created, I want to re-download all of the data.

I do not want the data updated more than once in a session. So I want to remove the observer immediately after getting the new data.

I've tried two things, but I'm not entirely sure how they work.

FIRDatabase.database().persistenceEnabled = true

Enabling persistence is great because just the one line of code caches everything downloaded from Firebase. Even when the app is not connected to the internet, it will pull the cached data and go about business as normal.

But my question about it is: Will the cache update when the data on Firebase updates? It appears that this is not the case.

When I go in and change a value on Firebase and relaunch the app, it just gives me the cached value, not the updated value.

So then I try this:

ref.keepSynced(true)

And this seems to work. I get the updated values when I relaunch the app.

But then my question is this: Does the app download the data every time the app launches (I do NOT want this) or just when it needs to be updated?

like image 628
bkSwifty Avatar asked Mar 25 '17 00:03

bkSwifty


1 Answers

Your app will synchronize data from Firebase Realtime Database whenever there is an active listener at a location in the database, and only when any data under that location changes. When you use keepSynced, you are effectively attaching a listener at location of the reference.

When your app process stops, all listeners are effectively removed. When your app process starts again, none of the old listeners are attached again. You have to execute code to get new listeners attached. If you do not attach new listeners, no new data will be synchronized. In other words, keepSynced does not establish a persistent synchronization at a location that lasts between app invocations. You have to ask for it every time.

Enabling persistence simply allows a listener to respond to cached data immediately without having to wait for data from the service. The listener will received the cached data first, then subsequent updates after that, as long as it's still attached and the data on the service is actually changing.

like image 123
Doug Stevenson Avatar answered Sep 27 '22 20:09

Doug Stevenson