Search code examples
angularrefresh-tokenng-idle

Angular 6 double subscribe issue


I'd like to issue a refresh token API call when an idle timeout ends in my app...

My incorrect code for doing so is:

idle.onIdleEnd.subscribe(() => {
            console.log('idle end reached');
            if (this.authStore.isAuthenticated()) {
                this.authService.refreshToken().subscribe(() => null);
            }

            this.activeModal.hide();
        });

However, this is for some reason exponentially triggering the refresh token, which is undesirable and ultimately creates a race condition with an invalid token being sent when a new one's been issued already (reads from local storage).

So when the idle timer fires once and i wiggle the mouse, refresh token fires once, however the 2nd time it fires twice, and the 3rd time it fires 4 times, how do I make it fire once per idle end?


Solution

  • Try unsubscribing from the observable when hiding the modal:

    private subscription: Subscription;
    
    this.subscription = idle.onIdleEnd.subscribe(() => {
        console.log('idle end reached');
        if (this.authStore.isAuthenticated()) {
            this.authService.refreshToken().subscribe();
        }
    
        this.activeModal.hide();
        this.subscription.unsubscribe();
    });