Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset Observable with a delay?

Tags:

angular

rxjs

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?

like image 426
Nxt3 Avatar asked Jan 25 '23 17:01

Nxt3


1 Answers

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

like image 151
Drenai Avatar answered Jan 28 '23 10:01

Drenai