Search code examples
rxjssubjectsubject-observer

Does a Subject safely unsubscribe its subscribers when it completes?


If I have this class with a subject that emits a single value during its life:

export class MyClass {
  myEmitter$: Subject<void> = new Subject();

  someMethod(){
    this.myEmitter$.next();
    this.myEmitter$.complete();
  }
}

and then in another class:

this.instanceOfMyClass.myEmitter.subscribe();

Should I unsubscribe from instanceOfMyClass.myEmitter$, given that the subject completes after emitting?


Solution

  • When you call complete on the subject, any subscribers will be automatically unsubscribed.

    If you look at the source for the subject's complete method:

    complete() {
      if (this.closed) {
        throw new ObjectUnsubscribedError();
      }
      this.isStopped = true;
      const { observers } = this;
      const len = observers.length;
      const copy = observers.slice();
      for (let i = 0; i < len; i++) {
        copy[i].complete();
      }
      this.observers.length = 0;
    }
    

    You'll see that the subject calls complete on each of its observers. And the Observable Contract states that:

    When an Observable issues an [error] or [complete] notification to its observers, this ends the subscription. Observers do not need to issue an [unsubscribe] notification to end subscriptions that are ended by the Observable in this way.