我是否需要完成一个主题才能被垃圾收集? [英] Do I need to complete a Subject for it to be garbage collected?

查看:16
本文介绍了我是否需要完成一个主题才能被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Angular 组件中遵循一个清理模式,如下所示:

I follow a cleanup pattern in my Angular components that looks like this:

class SomeComponent implements OnInit, OnDestroy {
    private destroy$ = new Subject();

    ngOnInit() {
        service.someStream().takeUntil(this.destroy$).subscribe(doSomething);
    }

    ngOnDestroy() {
        this.destroy$.next(true);
    }
}

这样做的好处是可以在组件销毁时自动取消订阅.

This has the benefit of automatically unsubscribing when the component is destroyed.

我的问题是:对 destroy$ 的引用是否会因为我没有调用 this.destroy$.complete() 而无限期地存在,或者它会不会得到 GC'ed 在父类被收集时?

My question is: Does a reference to destroy$ stick around indefinitely because I haven't called this.destroy$.complete(), or will it get GC'ed when the parent class is collected?

推荐答案

如果你查看 Subject.complete,你会找到答案:

If you look at the source for Subject.complete, you'll find the answer:

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 通知任何观察者,然后清除观察者数组.除非您有一个引用 Subject 的观察者/订阅者,否则 complete 实现中没有任何内容会影响 Subject> 可能会被垃圾收集.

Calling complete notifies any observers and then clears the array of observers. Unless you have an observer/subscriber that has a reference to the Subject, there is nothing in the complete implementation that would affect whether or not the Subject could be garbage collected.

RxJS 向订阅者推送通知.订阅者不持有对 observable 的引用;正好相反.所以,除非你已经明确地创建了一个持有对 Subject 的引用的订阅者——通过闭包或其他一些机制——没有必要调用 complete 进行垃圾收集目的.

RxJS pushes notifications to subscribers. Subscribers don't hold references to the observables; it's the other way around. So, unless you've explicitly created a subscriber that holds a reference to the Subject - via a closure or some other mechanism - there's no need to call complete for garbage-collection purposes.

这篇关于我是否需要完成一个主题才能被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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