We have several Angular services that subscribe to an event in the constructor. We are trying to determine whether it's necessary to unsubscribe from the event in the ngOnDestroy() method. Here's an example of the code:
import { Injectable, OnDestroy } from '@angular/core';
@Injectable()
export class DebuggerService implements OnDestroy {
private _subscriptions$: any = [];
constructor(private _localStorageService: LocalStorageService) {
this._subscriptions$.push(this._localStorageService.storageChanged.subscribe((event: StorageEvent) => {
//do something
}));
}
ngOnDestroy(): void {
for (let subscription$ of this._subscriptions$) {
subscription$.unsubscribe();
}
}
}
On the one hand, unsubscribing from the event in ngOnDestroy() seems like a good practice to do, especially for watchers because they will stick around even if you destroy a component.
On the other hand, a service is singleton in Angular. At most, only one instance of the service should ever exist at the same time, and it will be destroyed when the app is destroyed, so maybe unsubscribing not necessary?