Reputation: 1387
Let's assume we have two buttons. The first button executes the action with a delay of 1000ms, while the other executes it with a delay of 2000ms. When clicking a button, I want to wait for it's execution and only after that, allow actions from the other button.
For example, clicking button two, and then button one, should only result in the action two button being executed (basically the action of button1 will be ignored, because action2 has not yet been executed). How can that be achieved using the rxjs library?
const btnOne = document.querySelector('#btn1');
const obs1 = rxjs.fromEvent(btnOne, 'click').pipe(
rxjs.operators.delay(1000)
);
const btnTwo = document.querySelector('#btn2');
const obs2 = rxjs.fromEvent(btnTwo, 'click').pipe(
rxjs.operators.delay(2000)
);
const generalObs = rxjs.merge(obs1, obs2).pipe(
rxjs.operators.take(1),
rxjs.operators.repeat()
);
generalObs.subscribe(result => console.log(result.target));
Upvotes: 0
Views: 86
Reputation: 6441
Check this stackblitz: it demonstrates the use of the exhaustMap operator to achieve the behavior you describe.
https://stackblitz.com/edit/angular-a6spvp
The different map operators are amongst the most important and frequently used operators. Check the article below for a better explanation of what you can do with exhaustMap, switchMap, concatMap or mergeMap.
https://blog.angular-university.io/rxjs-higher-order-mapping/
Once you have read the article: use the stackblitz i posted and replace exhaustMap with switchMap, concatMap or mergeMap and see how that affects the behavior ;)
Upvotes: 1