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

前端 未结 2 1559
臣服心动
臣服心动 2020-12-09 12:48

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 t

相关标签:
2条回答
  • 2020-12-09 13:24

    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.

    0 讨论(0)
  • 2020-12-09 13:32

    After some time, I would like to add .02 to @Kato's answer:

    Opt to call snapshot.exists() instead of calling snapshot.val() === null. As the documentation points out, exists() is slightly more efficient than comparing snapshot.val() to null.

    And if you want to update data prefer to use the update() method rather then set(), as the last will overwrite your Firebase data. You can read more here.

    0 讨论(0)
提交回复
热议问题