简体   繁体   中英

Firebase Firestore: globally detect when there are pending writes

I've got a simple requirement to show a warning to the user if they leave the browser window while a pending write is happening in Firestore using a beforeunload listener:

window.addEventListener('beforeunload', e => {
  if (NO_PENDING_SAVES) return;      

  e.preventDefault();
  e.returnValue =
    'Your changes are still being saved. Are you sure you want to leave?';
}, {
  capture: true,
});

In Firestore using the Web SDK, how do I detect whether there are pending saves or not globally? There is a waitForPendingWrites() method on the Firestore object, but it would require polling and it's also asynchronous, so it won't work inside of beforeunload .

Solved doing this (async way) using Angular Framework and dependency "@angular/fire": "^7.4.1" :

export class FirebaseService {
 constructor(private db: AngularFirestore) {
 }
 pendingWrites(): Observable<any> {
    return defer(() => this.db.firestore.waitForPendingWrites())
 }

And then:

export class PendingWritesService {
 hasPendingWrites$: Observable<boolean>;

 constructor(
  private firebaseService: FirebaseService
 ){
  this.hasPendingWrites$ = this.somethingPending$();
 }

 somethingPending$(): Observable<boolean> {
  const timeEmmiter = timer(1000);
  return race(timeEmmiter, this.firebaseService.pendingWrites()).pipe(
    switchMap((pendingWrites, noPendingWrites) => {
     const arePendingsWrites = 0;
      return of(pendingWrites === arePendingsWrites);
   })
  )
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM