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

问题描述

我在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处理?

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将通知推送给订阅者.订户不持有对可观察对象的引用;相反.因此,除非您通过闭包或其他机制明确创建了一个对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.

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

09-18 06:04