adriancarriger / angularfire2-offline

🔌 A simple wrapper for AngularFire2 to read and write to Firebase while offline, even after a complete refresh.
https://angularfire2-offline.firebaseapp.com/
MIT License
207 stars 48 forks source link

How to verify if local data is synchronized? #69

Open thiagocarvp opened 7 years ago

thiagocarvp commented 7 years ago

I'm using AngularFire2 Offline in my Ionic application. I want to verify whether local data is already synchronized with Firebase. Does it have a function to check that?

adriancarriger commented 7 years ago

Hi @thiagocarvp, you can just use the regular Firebase promise like this:

const promise = this.afoDatabase.object('car').update({maxSpeed: 100});
promise.then(() => console.log('data saved to Firebase!'));

This promise tells you when your local data is synchronized with Firebase.

You might also like reading working with promises.

thiagocarvp commented 7 years ago

Thanks for response! Actually, I was looking for a function that verifies if whole data is already synchronized in my application.

adriancarriger commented 7 years ago

@thiagocarvp can you give me an example of what you'd like to do? I think I need a little bit more context. Thanks!

thiagocarvp commented 7 years ago

It would be like to verify if every promise in AngularFire2 Offline is settled, like this:

myclass {
  counter: number = 0;

  update() {
    this.counter++;
    const promise = this.afoDatabase.object('car').update({maxSpeed: 100});
    promise.then(() => {
      console.log('data saved to Firebase!');
      this.counter--;
    });
    promise.catch(() => {
      this.counter--;
    }
  }

  isSynchronized() {
    return this.counter == 0;
  }
}

But I think this approach will lead to concurrency problems, and in case of app be closed, promises will be lost.

thiagocarvp commented 6 years ago

If I am able to get the promises of emulated updates which are made when app starts, I can count remaining promises, like I said in the comment above. Is it possible to get these promises?

larssn commented 6 years ago

Not sure I follow your use case exactly, but you could consider using Promise.all()

Promise.all() will only resolve when ALL promises in the array resolves. If a single promise fails, it will throw a catchable error.

const promiseArr: Promise<any>[] = ... a promise array
Promise.all(promiseArr)
   .then(success => {})
   .catch(fail => {});
thiagocarvp commented 6 years ago

Thanks @larssn ! But in case of app would be killed, these promises (which are not resolved yet) would be lost. Then the app is open again, how could I get the promises for the updates which will be synchronized with Firebase when a connection is available?