简体   繁体   English

Angular rxjs 内存泄漏

[英]Angular rxjs memory leak

If I have a component and I want to unsubscribe using takeuntil, will switching from the below Before to After cause a memory leak (when using many subjects)如果我有一个组件并且我想使用 takeuntil 取消订阅,从下面的 Before 到 After 切换会导致内存泄漏(使用许多主题时)

Before

class OnInit, OnDestroy{
private subjectA: Subject<TypeA> = new Subject();

public subjectA$: Observable<TypeA> = this.subjectA.asObservable();

ngOnDestroy {
    this.subjectA.complete();
}
}

After

   class OnInit, OnDestroy{
    private subjectA: Subject<TypeA> = new Subject();
    private destroy$: Subject<boolean> = new Subject();
    
    public subjectA$: Observable<TypeA> = this.subjectA.asObservable.pipe(takeUntil(this.destroy$));
    
    onDestroy {
         this.destroy$.next(true);
         this.destroy$.unsubscribe();
    }
    }

The reason I ask is that the private subject never really is destroyed -- it just stops taking from it.我问的原因是私人主体从来没有真正被摧毁——它只是停止从它那里拿走。

There's a typo in the code.代码中有一个错字。 It should be "ngOnDestroy", not "onDestroy".它应该是“ngOnDestroy”,而不是“onDestroy”。

 Component implements OnDestroy {

  ngOnDestroy() {
    ...
  }
}

Also you may be interested to use ReplaySubject instead of Subject for destroy$ (in 99% cases it's not necessary, but in 1% of cases it could prevent "hard-to-catch" memory leaks).此外,您可能有兴趣使用ReplaySubject而不是Subject用于destroy$ (在 99% 的情况下没有必要,但在 1% 的情况下它可以防止“难以捕捉”的内存泄漏)。

In addition to the answer above,除了上面的答案,

This syntax isnt correct.此语法不正确。

public subjectA$: Observable<TypeA> = this.subjectA.asObservable(takeuntil(this.destroy$));

you should change this to你应该把它改成

public subjectA$: Observable<TypeA> = this.subjectA.asObservable().pipe(takeUntil(this.destroy$));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM