I am trying to use switchMap in rxjs to only emit the most recent observable and only once(the other observables should be cancelled). The goal to use this with the debounce operator, this is my start point. Now trying to make it so if I click the button multiple times I only get one emit as currently I will get as many emits as times I click the button without a > 1 second delay.(5 clicks then a 1 second wait is 5 console.logs at the same time)
Could someone point out to me how I can change this to get the desired result? I am trying to read through the posts here on switchMap but I find myself lacking =/ reading/watching more on switchMap, I am not even sure if this is the right way to accomplish what I am trying to.
const button = document.getElementById('debounce');
const click$ = fromEvent(button!, 'click');
click$.pipe(
startWith(null),
debounceTime(1000)
)
.subscribe(() => {
console.log('Button clicked after 1 second of inactivity')
// Emit your desired value or trigger your desired action here
});
So I tried.
const button = document.getElementById('debounce');
const click$ = fromEvent(button!, 'click');
click$.pipe(
startWith(null),
debounceTime(1000),
switchMap(event =>{
return timer(1000)
})
)
.subscribe(() => {
console.log('Button clicked after 1 second of inactivity')
// Emit your desired value or trigger your desired action here
});
but I can see that the switchMap here should be canceling previous click$ calls but not the inner timer calls....i think.
The results of this is that for each click the console log increments in increasing values. Button clicked after 1 second of inactivity 3 Button clicked after 1 second of inactivity 6 Button clicked after 1 second of inactivity 10 Button clicked after 1 second of inactivity ect...
the goal is for each click to always just return one log.(trying to get this right so I can use switchMap for searching other debounce things. :D)
Thank you for your time.