2019-10-18

Preventing multiple observables from firing from Redux-Observable

blogentry, javascript, selfnote, todayilearned

banner

Image by Brett Hondow from Pixabay

I've recently finished a basic course on RxJS. The main reason was to use Redux-Observable after watching this video, "Netflix JavaScript Talks - RxJS + Redux + React = Amazing!" referred to by Nicolas Marcora.

A basic example shows how to do "ping/pong", which was simple to implement.
But the problem is that, when you ping more than once, multiple observables are created.

After hours of struggle, I asked on the official Gitter page for Redux-Observable.

I will share what's done in public (Learn in Public) as the Gitter conversation is private.

Error Demo

Below shows multiple "ping/pong" actions being dispatched as you click on "PING" button.

The code that generated the mess above is shown below.

https://gist.github.com/dance2die/dc5105212fb76aa64fb0c41cc3389eec

For being a new RxJS (, which is a prerequisite for redux-observable) user, I couldn't figure it after hours of reading documentation and playing around.

Kevin Ghadyani generously spent time to review the code and provide a solution for the issue.

https://gist.github.com/dance2die/236f83b3e9777089f51fdb88bee0a1a9

1️⃣ uses switchMap, which implicitly cancels previous observable. So when PING button is clicked while the PING action is already dispatched, previous timer observable is canceled and a new one is started.

Kevin's forked Sandbox shows the fix.

https://codesandbox.io/s/basic-example-kgq57

Kevin also shows how to accomplish the same task using takeUntil.

https://gist.github.com/dance2die/3eecf3ac350c6470ab64078bb6b1e783