baiqilongma
baiqilongma

Reputation: 27

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)

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.

Upvotes: 0

Views: 370

Answers (2)

the_makeshift_dev
the_makeshift_dev

Reputation: 196

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$));

Upvotes: 1

George Kovalchuk
George Kovalchuk

Reputation: 82

There's a typo in the code. It should be "ngOnDestroy", not "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).

Upvotes: 2

Related Questions