blaster
blaster

Reputation: 8937

Expose a Subject to Callers But Be Notified when Subscriptions Drop to Zero

I have a service that I want to hand out a Subject (although it could be typed as an observable) as the result of a method call. This is straightforward, but what I really want is to be able to "detect" when its unsubscribe method is called (or since it could technically be handed out more than once to multiple subscribers, when its subscription count falls to zero). Is this possible?

Upvotes: 0

Views: 33

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21658

If you take a look at the source code to a behavior subject

https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts

you will see how to extend a subject. You could do the same thing to create your own kind of subject that instead of taking a start value it takes a callback to be run on unsubscribe that passes in the observer count. You would need to return a custom subscription object as unsubscribe is done from the subscription.

Upvotes: 1

Related Questions