Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sync offline database with Firebase when device is online?

I'm currently using angularJS and phonegap to build a test application for Android / iOS.

The app use only text data stored in a Firebase database. I want the app to have its own local database (used when the device is offline) and sometime (when the device is online) sync with a Firebase database.

The offline mode uses the storage API of phonegap/cordova. Could I just check the device's online state and backup the online database periodically ?

Any clues on how I can achieve this ? Last time a similar question was asked, the answer was "not yet"... (here)... because it focused on a hypothetical Firebase feature.

like image 616
Julien Tanay Avatar asked May 29 '13 09:05

Julien Tanay


People also ask

Can Firebase database work offline?

Querying Data OfflineThe Firebase Realtime Database stores data returned from a query for use when offline. For queries constructed while offline, the Firebase Realtime Database continues to work for previously loaded data.

What is simultaneous connections in Firebase?

A simultaneous connection is equivalent to one mobile device, browser tab, or server app connected to the database. This isn't the same as the total number of users of your app, because your users don't all connect at once.


1 Answers

If Firebase is online at the start and loses its connection temporarily, then reconnects later, it will sync the local data then. So in many cases, once Firebase is online, you can simply keep pushing to Firebase during an outage.

For true offline usage, you will probably want to monitor the device's state, and also watch .info/connected to know when Firebase connects.

new Firebase('URL/.info/connected').on('value', function(ss) {
   if( ss.val() === null ) /* firebase disconnected */
   else /* firebase reconnected */
});

The way to achieve this with the current Firebase toolset, until it supports true offline storage, would

  1. keep the local data simple and small
  2. when the device comes online, convert the locally stored data to JSON
  3. use set() to save the data into Firebase at the appropriate path

Additionally, if the app loads while the device is offline, for some reason, you can "prime" Firebase by calling set() to "initialize" the data. Then you can use Firebase as normal (just as if it were online) until it comes online at some point in the future (you would also want to store your local copy to handle the case where it never does).

Obviously, the simpler the better. Concurrent modifications, limits of local storage size, and many other factors will quickly accumulate to make any offline storage solution complex and time consuming.

like image 189
Kato Avatar answered Sep 25 '22 03:09

Kato