简体   繁体   中英

How to unsubscribe from Firestore realtime listener which is wrapped in an rxjs observable?

I have written a function that returns an observable that wraps the firestore onSnapshot method.

function getObservable() {
  return Observable.create(observer => {
      firebase.firestore().collection('users').onSnapshot(
        snapshot => observer.next(snapshot.docs),
      );
    });
  })
}

I am able to use this function and get updated docs as follows

const observable = getObservable()
const subscription = observable.subscribe(users => console.log('users'));

If I now call the subscription.unsubscribe() method, I will unsubscribe from the subscription. However, I will not subscribe from the onSnapshot listener.

Is there any way such that when I unsubscribe from the observable, I will automatically unsubscribe from the onSnapshot method.

From RxJS documentation ( http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-create ):

onSubscription can optionally return either a function or an object with unsubscribe method . In both cases function or method will be called when subscription to Observable is being cancelled and should be used to clean up all resources. So, for example, if you are using setTimeout in your custom Observable, when someone unsubscribes, you can clear planned timeout, so that it does not fire needlessly and browser (or other environment) does not waste computing power on timing event that no one will listen to anyways.

So, if I have understood this right, you may want to try something similar to this

function getObservable() {
  return Observable.create(observer => {
      const unsubscribe = firebase.firestore().collection('users').onSnapshot(
        snapshot => observer.next(snapshot.docs),
      );
      return unsubscribe;
    });
  })
}

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