I have a getDimensions
method which returns an Observable<string[]>
.
dimension.service.ts
public getDimensions(id: string): Observable<string[]> {
return this.service.loadDimensions(id);
}
reloader.service.ts
public update(idsToUpdate: string[]): void {
idsToUpdate.map(id => this.dimensionService.getDimensions(id)).pipe(
map(
newDimensions => this.updateDimensions(newDimensions)
)
).subscribe(); // ToDo: unsubscribe
}
Then in another part of the app, I'm calling this method inside update
method. The problem is, I don't know how to properly unsubscribe from getDimensions
. One possibly solution can be, to create a Subscription
and then in OnDestroy
call unsubscribe, but for me it's not good solution:
- this is a service, which I'm using in my entire application, so the
OnDestroy
hook will never occur - I'm calling the
update
method everyn
seconds, so there will be everyn
seconds a new subscription
Possible solution: (Not good)
reloader.service.ts
private subscriptions: Subscription = new Subscription();
...
...
public update(idsToUpdate: string[]): void {
const sub = idsToUpdate.map(id => this.dimensionService.getDimensions(id)).pipe(
map(
newDimensions => this.updateDimensions(newDimensions)
)
).subscribe(); // ToDo: unsubscribe
this.subscription.add(sub);
}
...
...
public onDestroy(): void {
this.subscription.unsubscribe();
}
EDIT:
As @jgerstle mentioned in his comment, if the observable completes (which is my case), there is no need to unsubscribe.