Angular Subscription Cleanup Strategies #1 (TakeUntil)
JS
S
JavaScriptDemonstrates using RxJS takeUntil operator to efficiently unsubscribe from observables in Angular, preventing memory leaks and improving performance.
1private onDestroy$: Subject<void> = new Subject();
2
3 public ngOnDestroy(): void {
4 this.onDestroy$.next();
5 this.onDestroy$.complete();
6 }
7
8
9 private getState(): void{
10 this.generatorService.data$.pipe(takeUntil(this.onDestroy$)).subscribe((state) => {
11 if (state){
12 this.state = state;
13 }
14 });
15 }Created on 1/22/2021