我在我的 Angular 组件中遵循如下所示的清理模式:
class SomeComponent implements OnInit, OnDestroy {
private destroy$ = new Subject();
ngOnInit() {
service.someStream().takeUntil(this.destroy$).subscribe(doSomething);
}
ngOnDestroy() {
this.destroy$.next(true);
}
}
这有利于在组件被销毁时自动取消订阅。
我的问题是:对 destroy$
的引用是否会无限期地存在,因为我没有调用 this.destroy$.complete()
,或者它会得到 GC '在收集父类时?
最佳答案
如果您查看 Subject.complete
的来源,你会找到答案:
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
可以被垃圾收集。
RxJS 向订阅者推送通知。订阅者不持有对可观察对象的引用;恰恰相反。因此,除非您通过闭包或其他机制明确创建了一个订阅者,该订阅者持有对 Subject
的引用 - 没有必要为垃圾收集调用 complete
目的。
关于angular - 我是否需要完成一个 Subject 才能被垃圾收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44289859/