Subject.complete() 是否取消订阅所有听众? [英] Does Subject.complete() unsubscribe all listeners?

查看:22
本文介绍了Subject.complete() 是否取消订阅所有听众?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个方法构建了一个简单的确认对话服务(Angular 2):

I build a simple confirmation dialog service (Angular 2) with this method:

confirm(body?: string, title?: string): Subject<void> {
    this.confirmation = new Subject<void>();
    // ... show dialog here... "are you sure?"
    return this.confirmation;
}

_onYesClicked() {
  // ... closing the dialog
  this.confirmation.next();
  this.confirmation.complete();
} 

_onNoClicked() {
  // ... closing the dialog
  this.confirmation.complete();
}

用法:

confirmationService.confirm().subscribe(() => alert("CONFIRMED"));

如果有人使用该服务,他会返回一个 Subject(它是一个 Observable)并且可以subscribe()"到它.单击是"时会调用订阅,因此已给出确认...

If someone uses the service, he gets a Subject (which is an Observable) returned and can "subscribe()" to it. The subscription is called when "yes" is clicked and therefore the confirmation was given...

这是正确的方法吗?更重要的是......是否会调用

Is this the correct way to do this? And more important... will the call to

this.confirmation.complete();

取消订阅已订阅的侦听器,从而防止任何拖延的引用(内存泄漏)?

unsubscribe the subscribed listeners and therefore prevent any lingering references (memory leakage)?

推荐答案

如果你想确定它删除了所有的观察者,你可以在 https://github.com/ReactiveX/rxjs/blob/master/src/internal/Subject.ts#L91.它在所有观察者上调用 complete()(观察者通常只是实现 观察者接口),然后设置this.observers.length = 0;.所以答案是肯定的.

If you want to be sure it removes all Observers you can check it for yourself in https://github.com/ReactiveX/rxjs/blob/master/src/internal/Subject.ts#L91. It calls complete() on all Observers (Observers are typically just dumb objects implementing Observer interface) and then sets this.observers.length = 0;. So the answer is yes.

您的方法是有效的,它与 Angular2 经常使用 EventEmitter 所做的基本相同.您可以改进的一件事是开始使用 asObservable() 暴露 Subject 时.这将隐藏您在下面使用 Subject 并仅返回常规 Observable 的事实.这样您就不会让您的用户意外(或误会)尝试调用 next()complete()error() 在您的 Subject 上.

Your approach is valid, it's basically the same as Angular2 regularly does with EventEmitter. Just one thing you can improve is start using asObservable() when exposing Subjects. This will hide the fact that you're using a Subject underneath and return just a regular Observable. This way you don't let your users to by accident (or from misunderstanding) try to call next() , complete() or error() on your Subject.

关于内存泄漏,这必须由 RxJS 处理,所以你不必担心,如果有问题,作者可能会在你之前注意到.

Regarding memory leakage, this has to be handled by RxJS, so you shouldn't worry about it and if there's a problem the authors would probably notice it before you.

也看看这个:Observable vs Subject and asObservable

这篇关于Subject.complete() 是否取消订阅所有听众?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆