Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase how to detect if cached data is available

I have an application that pulls some simple data from Firebase Realtime Database, and to make things simple here is the flow that I want to have.

If phone is connected to the internet:

  • Get the data from the firebase database

If phone is offline

  • If there is data in firebase cache -> get data from cache
    • If there is nothing in firebase cache -> show some default data stored locally in app

The problem is that I don't see possible way to detect if data is available in firebase cache. So when phone is offline I cannot see if I should display the locally stored data or cache from firebase database.

like image 475
ibrcic Avatar asked Feb 16 '17 09:02

ibrcic


People also ask

Does Firebase cache read?

This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data.

How do I know if my DataSnapshot is empty?

You can use hasChildren() to determine if a DataSnapshot has any children. If it does, you can enumerate them using forEach() . If it doesn't, then either this snapshot contains a primitive value (which can be retrieved with val() ) or it is empty (in which case, val() will return null ).

How do I check my Firebase Realtime Database?

To see your current Realtime Database connections and data usage, check the Usage tab in the Firebase console. You can check usage over the current billing period, the last 30 days, or the last 24 hours.

Does Firebase storage cache images?

If there's no cache, then the images will be requested from Firebase Storage, where the images can also be cached if you specified the cacheControl property in file metadata or if you is using Firebase Hosting with custom header Cache-Control for images.


1 Answers

Agree above answer, Firebase will do it for you, if you do it in the right way. In order to solve your problem, you should understand the difference between the two approaches of firebase offline cache - reading-from-memory and reading-from-disk.

Read this article -> https://pamartinezandres.com/lessons-learnt-the-hard-way-using-firebase-realtime-database-c609b52b9afb

in your case, just add, FirebaseDatabase.getInstance().setPersistenceEnabled(true); to enable reading from disk

and add yourReferenceForFirebase.keepSynced(true); to keep the data synched

then your app will work as you expected.

But, only this part: "If there is nothing in firebase cache -> show some default data stored locally in app", seems impossible.

like image 161
Azamat Mahkamov Avatar answered Oct 22 '22 12:10

Azamat Mahkamov