Subject 在完成后是否安全地退订其订阅者?

Does a Subject safely unsubscribe its subscribers when it completes?

如果我有这个 class 有一个在其生命周期中发出单一值的主题:

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

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

然后在另一个 class:

this.instanceOfMyClass.myEmitter.subscribe();

鉴于主题在发射后完成,我是否应该取消订阅 instanceOfMyClass.myEmitter$

当您就此主题致电 complete 时,所有订阅者都将自动退订。

如果您查看主题 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;
}

您会看到对象对其每个观察者调用 completeObservable Contract 指出:

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.