Reputation: 29
I want to trigger an async action via button Async increment
but cancel it by clicking button cancel
.
My code with race
of rxjs
does not work.
Is there any way to implement it?
https://codesandbox.io/s/zk5oy3zj7x
Upvotes: 0
Views: 506
Reputation: 2116
welcome.
switchMap
cancel the previous request (completing the previous inner observable) if a new request comes before the previous is completed.
If you want to cancel request with a new stream, you could merge your stream with the "action one", and let switchMap to decide what to do.
merge(
increment$.pipe(mapTo(true)),
cancelIncrement$.pipe(mapTo(false))
).pipe(
switchMap((run) => new Promise(resolve => {
if(run)
setTimeout(() => resolve(2), 2000);
}))
).subscribe(console.log);
Upvotes: 1