Unsubscribe techniques in Angular

Anh-Thi Dinh
draft
For HTTP Calls, no need to unsubscribe.

Using a list subscriptions

1import { Subscription } from 'rxjs';
1private subscriptions: Subscription[] = [];
1this.subscriptions.push(
2  // subscriptions
3);
1ngOnDestroy(): void {
2  this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
3}

Using takeUntil, takeWhile

1import { debounceTime, distinctUntilChanged, filter, takeUntil } from 'rxjs/operators';
1private destroy$ = new Subject();
1ngOnDestroy(){
2  this.destroy$.next();
3  this.destroy$.complete();
4}
1// someInput: FormControl = new FormControl('');
2this.someInput.valueChanges
3  .pipe(
4		debounceTime(1000),
5    distinctUntilChanged(),
6    takeUntil(this.destroy$)
7	).subscribe(val => {...});
Loading comments...