Angular and RxJs: handling expiration of verification code

I have a simple component to verify user's email. It consists of "Send Email" (that sends email with code) button, text input to enter sent code and "Verify" button that sends code to back for verification. Berification code expires in 5 minutes. And if I resend email new code expires in 5 minutes after resend.

I'm using OnPush change detection strategy so everything is handled with async pipes. The observable wrapping "Send Email" request is passed to template as async pipe. I want to have an other observable that will emit something (e.g. true) when 5 minutes passed. Yes, I can use delay operator in the way like the following

expired$ = sendObservable$.pipe(delay(5 * 60 * 1000), mapTo(true))

But. What if user decide to resend email? How can I restart these 5 minutes from the beginging?

And yes, I understand that all of that is somewhat strange. Maybe there's totaly different way to handle expiration of code using observables and async pipes?

1 answer

  • answered 2021-02-23 00:02 Petr Averyanov

    debounceTime delays values emitted by the source Observable, but drops previous pending delayed emissions if a new value arrives on the source Observable. This operator keeps track of the most recent value from the source Observable, and emits that only when dueTime enough time has passed without any other value appearing on the source Observable. If a new value appears before dueTime silence occurs, the previous value will be dropped and will not be emitted on the output

    So, simply:

    expired$ = sendObservable$.pipe(debounceTime(5 * 60 * 1000))