Reputation:
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.
Upvotes: 1
Views: 1643
Reputation: 17762
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;
});
})
}
Upvotes: 5