Mena
Mena

Reputation: 3385

Firebase realtime database: How to stop offline write? (Best approach)

Currently, in order to prevent write to Firebase after returning back from offline, I check for internet connectivity before every write operation. And by that I do not mean just checking for network connectivity, but also if there is actual internet access available. I ping google.com in order to find out.

I do not think this is the best way to do that.

So, what is the best practice to just tell Firebase not to cache any write operations when there is no internet connection available and just preview a plain simple "No internet connection available" message?

Upvotes: 1

Views: 1004

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317487

If you really must make your application unusable when the user's device even temporarily loses its connectivity, you will have to add a listener to a special location called /.info/connected. It will tell you when the SDK thinks it has lost its connected. This is described in the documentation. You will have to write code to make your app behave the way you want when your listener is notified like this.

However, your application may have still written data in the time it took from the moment the connection to became stalled, before the SDK makes a decision that the connection is actually gone. And those writes will still be synchronized.

It's better to just make your application usable offline, and notify the user when their data isn't yet synchronized due to being offline.

Upvotes: 3

Alex Mamo
Alex Mamo

Reputation: 138824

So, what is the best practice to just tell Firebase not to cache any write operations when there is no internet connection

You cannot tell Firebase not to add the write operation to a queue while offline. This is one of the most important features of the Firebase realtime database. So Firebase applications will also work even if your app temporarily loses its network connection. That's the beauty of this database.

By default, offline persistence is disabled. If you have enabled persistence then the simplest way to disable, it would be using the following line of code:

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

This way you tell Firebase that you don't need any cached data at all so there will be no writing pending opertions but unfortunately you can tell to stop caching data only while offline.

Upvotes: 2

Related Questions