RandomUs1r
RandomUs1r

Reputation: 4190

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?

Upvotes: 0

Views: 762

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18369

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();
});

Upvotes: 2

Related Questions