I'm trying to figure out how to "reset" a previous Observable that has a delay. My goal is such that when I click a button, it runs an action; at the end of that action, after waiting a defined amount of time, the action runs finalize to reset a value.
Here is a Stackblitz of what I mean.
If I click "Save new event", it will display a number. After 3 seconds, the number will disappear. The issue is if I click it once, it starts the delay--but then if I click it again after 1 second has passed, it will display the new number--but then 2 seconds later the number disappears since the first Observable sets {saveSuccess: null}.
Is there some RXJS magic that can accomplish what I want to do?
Yes, there is indeed some magic that will cancel the previous delay on each new click (I think that's what you're after)
You need to use a Subject at the class level, and use next on the subject for each click. The subject should be set up in the constructor (or ngOnInit) as follows, with the tap operators inside the pipe
this.subject.pipe(
switchMap(value => {
return timer(1000).pipe(...)
}),
tap(...)
).subscribe()
The switchMap will cancel the previous timer on each subsequent click
Note: timer with an integer value works the same as a delay, but is itself an observable, rather than an operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With