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

查看:316
本文介绍了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)?

推荐答案

如果要确保它删除了所有观察者,可以在观察者的愚蠢对象.界面),然后设置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的事实.这样,您就不会让用户偶然(或出于误解)尝试在Subject上调用next()complete()error().

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.

也请看一下:可观察与主体和可观察

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

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