I'm trying to use Rxjs as a way to manage garbage collection in a large state tree.
How can I create an operator that takes a callback function that is triggered every time the number of subscribers to the observable alters?
Due to the RxJS architecture an observable source can implement any cleanup logic whenever unsubscribe is called. For example, when RxJS is used in the context of a Node.js application you can model file reading using observable streams. Unsubscribing in this scenario would mean releasing the file handle. When unsubscribing is not required
An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.
The answer to that question is, “Only when you absolutely have to.” Because (among other reasons) if you don’t subscribe, you don’t have to unsubscribe. RxJS in Angular: When To Subscribe? (Rarely) When should you subscribe? The answer to that question is, “Only when you absolutely have to.”
Due to the RxJS architecture an observable source can implement any cleanup logic whenever unsubscribe is called. For example, when RxJS is used in the context of a Node.js application you can model file reading using observable streams.
Multiple ways, all involve hiding your subject and giving consumers a wrapped observable:
Want to know when something subscribes to your subject?
const subject = new Subject();
const observable = Observable.defer(() => {
someoneJustSubscribed();
return subject;
});
return observable;
Want to know when someone unsubscribes?
const subject = new Subject();
const observable = subject.finally(() => someoneJustUnsubscribed());
return observable;
Want to know both?
const subject = new Subject();
const observable = Observable.create(observer => {
someoneJustSubscribed();
const sub = subject.subscribe(observer);
return () => {
someoneJustUnsubscribed();
sub.unsubscribe();
}
});
return observable;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With