gpt4 book ai didi

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

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

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

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

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

然后在另一个类中:

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;
}

您会看到主题对其每个观察者调用 complete。和 Observable 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.

关于rxjs - Subject 在完成后是否安全地退订其订阅者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45763986/

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