Unsubscribe from Observables when component gets destroyed

JS
S
JavaScript

https://github.com/ngneat/until-destroy A neat way to unsubscribe from observables when the component destroyed

1npm install @ngneat/until-destroy
2import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
3
4// Example 1
5this.character$.pipe(
6  distinctUntilChanged(),
7  untilDestroyed(this),
8);
9
10// Example 2
11interval(1000)
12  .pipe(untilDestroyed(this))
13  .subscribe();
14
15// Example 3
16@UntilDestroy({ checkProperties: true })
17@Component({})
18export class HomeComponent {
19  // We'll dispose it on destroy
20  subscription = fromEvent(document, 'mousemove').subscribe();
21}
22
23// Example 4
24@UntilDestroy({ arrayName: 'subscriptions' })
25private readonly subscriptions: Subscription[] = [];
26this.subscriptions.push(gridSubscription);
27this.subscriptions.push(codeSubscription);
28
29// Example 5
30this.code$
31  .pipe(
32    untilDestroyed(this),
33  )
34  .subscribe((code) => {
35    this.paymentForm.patchValue({ code });
36  });

Created on 3/4/2020