每当主题的最后一个订阅者取消订阅时,我都需要运行一些清理代码。我该怎么做?
这是我到目前为止所做的,但在我看来,这不是一个很好的方法。当然有一种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);
}
}