Does Subject.complete() unsubscribe all listeners?

前端 未结 1 2007
走了就别回头了
走了就别回头了 2020-12-29 19:11

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

confirm(body?: string, title?: string): Subject {
    this.confirmatio         


        
相关标签:
1条回答
  • 2020-12-29 19:39

    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.

    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.

    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.

    Also have a look at this: Observable vs Subject and asObservable

    0 讨论(0)
提交回复
热议问题