Search code examples
rxjsobserverssubject

Invoke method when no observers for RxJs Subject


How to invoke a method when all the observers have unsubscribed from a subject.

Update

const alphaStore = new BehaviourSubject(0);
observer1 = alphaStore.subscribe(console.log);
observer2 = alphaStore.subscribe(console.log);

And when all of these observers unsubscribe. I want a method to be invoked. Like...

Observer1 unsubscribed

Observer2 unsubscribed

All observers left


Solution

  • What you describe already does the finalize() operator. Better said finalize() calls its callback when the chain disposes which means it's called when all observers unsubscribes, the chain completes or errors.

    const subject = new Subject();
    const shared = subject.pipe(
      finalize(() => console.log('finalize')),
      share(),
    );
    

    https://stackblitz.com/edit/rxjs-rebfba

    When all observers unsubscribe share() unsubscribes from its source which triggers finalize().

    Currently there's no way to distinguish why finalize() was invoked. See this issue https://github.com/ReactiveX/rxjs/issues/2823 and examples there on how to do it.