When should I store the Subscription
instances and invoke unsubscribe()
during the NgOnDestroy life cycle and when can I simply ignore them?
Following the answer by @seangwright, I've written an abstract class that handles "infinite" observables' subscriptions in components:
import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { PartialObserver } from 'rxjs/Observer';
export abstract class InfiniteSubscriberComponent implements OnDestroy {
private onDestroySource: Subject = new Subject();
constructor() {}
subscribe(observable: Observable): Subscription;
subscribe(
observable: Observable,
observer: PartialObserver
): Subscription;
subscribe(
observable: Observable,
next?: (value: any) => void,
error?: (error: any) => void,
complete?: () => void
): Subscription;
subscribe(observable: Observable, ...subscribeArgs): Subscription {
return observable
.takeUntil(this.onDestroySource)
.subscribe(...subscribeArgs);
}
ngOnDestroy() {
this.onDestroySource.next();
this.onDestroySource.complete();
}
}
To use it, just extend it in your angular component and call the subscribe()
method as follows:
this.subscribe(someObservable, data => doSomething());
It also accepts the error and complete callbacks as usual, an observer object, or not callbacks at all. Remember to call super.ngOnDestroy()
if you are also implementing that method in the child component.
Find here an additional reference by Ben Lesh: RxJS: Don’t Unsubscribe.