如何检测rxjs订户何时取消订阅?

时间:2017-09-07 13:35:18

标签: rxjs

每当主题的最后一个订阅者取消订阅时,我都需要运行一些清理代码。我该怎么做?

这是我到目前为止所做的,但在我看来,这不是一个很好的方法。当然有一种reactive方式可以做到这一点吗?

export class TestSubject<T> extends BehaviorSubject<T> {
  protected _subscribe(subscriber: Subscriber<T>): Subscription {
    const originalSubscription = super._subscribe(subscriber);
    return new TestSubjectSubscription<T>(
      this,
      subscriber,
      originalSubscription,
      (observer) => this.registerUnsubscription(observer));
  }

  private registerUnsubscription(subscriber: Observer<T>) {
  }

}

export class TestSubjectSubscription<T> extends SubjectSubscription<T> {
  constructor(
    subject: TestSubject<T>,
    subscriber: Observer<T>,
    private inner: Subscription,
    private notifyUnsubscribed: (subscriber: Observer<T>) => void) {
    super(subject, subscriber);
  }

  unsubscribe() {
    this.inner.unsubscribe();
    this.notifyUnsubscribed(this.subscriber);
  }
}

1 个答案:

答案 0 :(得分:3)

some of the built-in examples of geom2trace可用于在流完成后调用回调(错误/完成/取消订阅)