Reputation: 161
I want to make sure all used resources are being properly disposed and avoid memory leaks angular 8 app
Upvotes: 0
Views: 2306
Reputation:
Update
Found the source: https://medium.com/angular-in-depth/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0
Initial answer
A pattern I've seen and used many times:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({})
class Component implements OnInit, OnDestroy {
private unsubscribe$ = new Subject<void>();
ngOnInit(): void {
yourObservable.pipe(takeUntil(unsubscribe$)).subscribe();
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
Upvotes: 1