I came across a wonderful feature of Firebase offline feature. I integrated that in my app just by writing one line of code in my main.dart file after initializing Firebase await FirebaseDatabase.instance.setPersistenceEnabled(true);
Question 1 :
I couldn't able to understand the database.keepSynced(true)
function because without using this line of code, my app is persisting old as well as fetching new updated data, so what this exactly does ?
Question 2 :
How could I prevent the write operations when a user is offline, because I read that after setting persistence enabled, it makes a queues of write operations and update them when user gets online, so how could I stop this ?
Question 3 :
Is this persistence feature going to work in IOS device as well or need some permission settings first ?
Thanks
CodePudding user response:
When you call FirebaseDatabase.instance.setPersistenceEnabled(true)
you're allowing Firebase to create a local file on the device where it persists any data it's recently read, and all writes that are pending while the device is offline.
When you call keepSynced(true)
on a node, you are telling the SDK to always keep that node synchronized. It essentially creates a onValue
listener on the node without any handler code, so you're purely doing this to keep the data synchronized for when the device does go offline.
By combining keepSynced(true)
with setPersistenceEnabled(true)
, you're specifying that you want the app to continue working when it's offline across restarts, and which data is needed for that.
If you call keepSynced(true)
on the root of your database, you're telling the SDK to synchronize all data in the database to the disk cache. While this may initially be a quick way to get offline mode for your app working, it typically won't scale when you more people start using your app.
If you only want to allow write operations while the client has a connection to the database backend, you can register a local listener to the .info/connected
node, which is a true
value when there is a connection and false
otherwise.
Note that Firebase doesn't require this, as it queues the pending writes and executes them when the connection is restored. In general, I'd recommend working with the system here instead of against it, and also trying to make your app work gracefully in the offline scenario. In many cases there is no need to disable functionality while the app is offline.
Offline disk persistence is available on Android and iOS, but not on web.