How to unsubscribe RxJs Observable in Angular

Each time you call subscribe method on RxJs Observable, you should (most of the time) also call unsubscribe. See how you can do it in Angular components.

October 2, 2022 angularangular-15

Unsubscribe on ngOnDestroy hook

Advantages:

Disadvantages:

1
@Component({})
2
export class MyComponent implements OnInit, OnDestroy {
3
private sub1!: Subscription;
4
private sub2!: Subscription;
5
6
ngOnInit(): void {
7
this.sub1 = interval(1000).subscribe();
8
this.sub2 = interval(1000).subscribe();
9
}
10
11
ngOnDestroy(): void {
12
this.sub1.unsubscribe();
13
this.sub2.unsubscribe();
14
}
15
}

Unsubscribe on ngOnDestroy hook with subscriptions container

Advantages:

Disadvantages:

1
@Component({})
2
export class MyComponent implements OnInit, OnDestroy {
3
private subs = new Subscription();
4
5
ngOnInit(): void {
6
const sub1 = interval(1000).subscribe();
7
const sub2 = interval(1000).subscribe();
8
9
this.subs.add(sub1);
10
this.subs.add(sub2);
11
}
12
13
ngOnDestroy(): void {
14
this.subs.unsubscribe();
15
}
16
}

Unsubscribe with async pipe

Advantages:

Disadvantages:

1
@Component({
2
template: `
3
<ng-container *ngIf="interval1$ | async"></ng-container>
4
<ng-container *ngIf="interval2$ | async"></ng-container>
5
`,
6
})
7
export class MyComponent {
8
interval1$ = interval(1000);
9
interval2$ = interval(1000);
10
}

Complete stream with takeUnitl operator

Advantages:

Disadvantages:

1
@Component({})
2
export class MyComponent implements OnInit, OnDestroy {
3
private destroy$ = new Subject<void>();
4
5
ngOnInit(): void {
6
interval(1000).pipe(takeUntil(this.destroy$)).subscribe();
7
interval(1000).pipe(takeUntil(this.destroy$)).subscribe();
8
}
9
10
ngOnDestroy(): void {
11
this.destroy$.next();
12
this.destroy$.complete();
13
}
14
}

Unsubscribe/Complete with destroyable local service

Thanks to destroyable local service you can move unsubscribe logic outside the component.

Advantages:

Disadvantages:

1
@Injectable()
2
export class Unsubscriber extends Subject<void> implements OnDestroy {
3
private subs = new Subscription();
4
5
set add(sub: Subscription) {
6
this.subs.add(sub);
7
}
8
9
ngOnDestroy(): void {
10
this.next();
11
this.complete();
12
this.subs.unsubscribe();
13
}
14
}
1
@Component({
2
providers: [Unsubscriber],
3
})
4
export class MyComponent implements OnInit {
5
constructor(private unsubscriber: Unsubscriber) {}
6
7
ngOnInit(): void {
8
// with takeUntil pattern
9
interval(1000).pipe(takeUntil(this.unsubscriber)).subscribe();
10
11
// with unsubscribe pattern
12
this.unsubscriber.add = interval(1000).subscribe();
13
}
14
}

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment