Guarantee Ordering of Events with RxJS

Share this video with your friends

Send Tweet

Did it ever happen to you that you had to make sure certain user events are processed in order? Maybe some of those events were even async. Guaranteeing ordering can be quite tricky, unless you know some RxJS magic. In this lesson I'll briefly show you how to use RxJS's concatMap and switchMap operators to make sure events are processed in the right ordering and thus to prevent our UI from getting out of sync.

Julia Passynkova
~ 5 years ago

Hi Juri, switchMap is a good solution to cancel add/remove of the same option But what about a scenario when user quickly clicks on option2 and after that option1? You will expect option2 and option1 in Result view? However, switchMap will cancel processing of option2 and in the Result view only option1 will be displayed.

Juri Strumpflohnerinstructor
~ 5 years ago

Hey Julia, good catch. In fact, after publishing the video yesterday I recognized there might be this race condition. There's another solution one can implement to optimize the event procesing, using a combination of mergeMap and takeUntil. I'll update my blog post and this Egghead video accordingly, but only next week probably as I won't be able to do it earlier. But I'll let you know :)

Julia Passynkova
~ 5 years ago

Hi Juri,

I made a change that supports switchMap for multiple options. You can see it here:

https://stackblitz.com/edit/blog-guarantee-order-switchmap?file=app%2Fcheckbox-configurable-example.ts

=== Julia Passynkova

LinkedIn: https://ca.linkedin.com/in/juliapassynkova Github: https://github.com/ipassynk Medium: https://medium.com/@juliapassynkova Stackoverflow : http://stackoverflow.com/users/6922095/julia-passynkova

Juri Strumpflohnerinstructor
~ 5 years ago

Hey Julia!

Great, but I think you linked the wrong Stackblitz. You my original one 😅. You probably forgot to save or need to fork it first.

Julia Passynkova
~ 5 years ago

Yep, I forgot. Here it is https://stackblitz.com/edit/blog-guarantee-order-switchmap-fq92o5?file=app/checkbox-configurable-example.ts

=== Julia Passynkova

LinkedIn: https://ca.linkedin.com/in/juliapassynkova Github: https://github.com/ipassynk Medium: https://medium.com/@juliapassynkova Stackoverflow : http://stackoverflow.com/users/6922095/julia-passynkova

Juri Strumpflohnerinstructor
~ 5 years ago

@Julia: thanks for sharing. Interesting approach and a bit similar to what I just updated on my blog post: https://juristr.com/blog/2019/01/Guarantee-Event-Order-with-RxJS/. What I am using is basically a mergeMap and on the inner Observable a takeUntil to filter for "same id events".

(I'll also update the Egghead video, but only next week)