From my understanding of Angular and RxJs there are two ways to terminate Observables. You can unsubscribe()
from them or use takeUntil()
and complete()
. Below are examples of each approach (in pseudocode).
The unsubscribe() approach
private _id: number;
private _subscriptions: Subscription[] = [];
constructor(private _route: ActivatedRoute) {
this._getId();
}
public ngOnDestroy(): void {
this._subscriptions.forEach(
subscription => subscription.unsubscribe()
);
}
private _getId(): void {
this._subscriptions.push(
this._route.params.subscribe(params => this._id = +params['id'])
);
}
The takeUntil() and complete() approach
private _id: number;
private _ngUnsubscribe: Subject<void> = new Subject<void>();
constructor(private _route: ActivatedRoute) {
this._getId();
}
public ngOnDestroy(): void {
this._ngUnsubscribe.next();
this._ngUnsubscribe.complete();
}
private _getId(): void {
this._route.params.takeUntil(this._ngUnsubscribe).subscribe(
params => this._id = +params['id']
);
}
In Angular, is there a preferred way to terminate Observables?
ngOnDestroy
, which you are doing. The only thing I might add is to check that the values are "truthy", meaning not null or not undefined, otherwise you will get an error trying to callunsubscribe()
. – Riffe