My Angular service has three attributes and two functions:
timerSubscription: Subscription;
pollingSubscription: Subscription;
incrementTimerSubscription: Subscription;
async startTimer(idTask: number) {
this.timerSubscription = this.folderService
.getTimerForTemplate(idTask)
.pipe(
tap(res => this.timer$.next(res.seconds)),
switchMap(() => this.folderService.startTimerForTemplate(idTask))
)
.subscribe(() => {
this.setMyState({ idTask: idTask, isTimerStarted: true });
this.incrementTimerSubscription = interval(1000)
.pipe(
tap(() => {
this.timer$.next(this.timer$.value + 1);
})
)
.subscribe();
this.pollingSubscription = interval(20000)
.pipe(
switchMap(() => {
return this.folderService.incrementTimerForTemplate(idTask);
})
)
.subscribe();
});
}
incrementAndStartTimer(idTaskToIncrement: number, idTaskToStart: number, automaticSwitch?: boolean) {
if (this.timerSubscription) {
this.timerSubscription.unsubscribe();
}
if (this.pollingSubscription) {
this.pollingSubscription.unsubscribe();
}
if (this.incrementTimerSubscription) {
this.incrementTimerSubscription.unsubscribe();
}
if (automaticSwitch) {
this.folderService
.incrementTimerForTemplate(idTaskToIncrement, automaticSwitch)
.pipe()
.subscribe(() => {
this.startTimer(idTaskToStart);
});
} else {
this.folderService
.incrementTimerForTemplate(idTaskToIncrement)
.pipe()
.subscribe(() => {
this.startTimer(idTaskToStart);
});
}
}
After successfully calling the startTimer function, I face an issue when trying to call it again after using the incrementAndStart function to unsubscribe from existing subscriptions. This problem arises because the previous subscriptions have been unsubscribed. How can I resolve this issue?