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?
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?
Share Improve this question edited Sep 15, 2017 at 21:23 Vadim Kotov 8,2848 gold badges50 silver badges63 bronze badges asked Sep 15, 2017 at 14:53 Peter MorrisPeter Morris 23.3k12 gold badges97 silver badges166 bronze badges1 Answer
Reset to default 15Multiple 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;