gpt4 book ai didi

rxjs - 如何检测 rxjs 订阅者何时取消订阅?

转载 作者:行者123 更新时间:2023-12-01 22:34:09 31 4
gpt4 key购买 nike

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

这是我到目前为止所拥有的,但在我看来这不是一个好的方法。当然有一种响应式(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);
}
}

最佳答案

.finally()可用于在流完成后调用回调(错误/完成/取消订阅)

关于rxjs - 如何检测 rxjs 订阅者何时取消订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46097801/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com