How to synchronize a standalone database with Firebase when the device is online?

I am currently using angularJS and phonegap to create a test application for Android / iOS.

The application uses only text data stored in the Firebase database. I want the application to have its own local database (used when the device is disconnected) and someday (when the device is connected to the network) synchronization with the Firebase database.

In offline mode, the phonegap / cordova storage API is used. Can I just check the online status of the device and periodically back up the online database?

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

+7
source share
2 answers

If Firebase is online at the beginning and temporarily loses its connection and then reconnects, it will synchronize local data. Therefore, in many cases when Firebase is online, you can simply continue to insist on Firebase during the crash.

For real-time use, you probably want to monitor the status of the device, and also watch .info/connected to know when Firebase is connecting.

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

A way to achieve this with the current Firebase toolkit, until it supports true offline storage, would be

  • keep local data simple and small
  • when the device connects to the network, convert the locally stored data to JSON
  • use set() to save data in Firebase on the appropriate path.

Also, if the application loads when the device is offline, for some reason you can “just start” Firebase by calling set () to “initialize” the data. Then you can use Firebase as usual (just as if it were online) until it appears on the network at some point in the future (you will also want to keep your local copy to deal with the case when it never does not work).

Obviously, the simpler the better. Simultaneous changes, local storage size restrictions, and many other factors quickly accumulate to make any stand-alone storage solution complex and time-consuming.

+10
source

After a while, I would like to add .02 to @Kato's answer:

Call snapshot.exists() instead of calling snapshot.val() === null . As the documentation points out, there is () a little more efficiency than comparing snapshot.val () with null.

And if you want to update the data, you prefer to use the update() method rather than set() , since the latter will overwrite your Firebase data. You can read it here .

0
source

All Articles