DEV Community

Oleksandr Sachuk
Oleksandr Sachuk

Posted on

Handle async actions by the RxJS and Redux-observable

Table Of Contents

Code example

RxJS and Redux-observable are very useful to handle async actions.
I would like to show an example usage RxJS and Redux-observable in the react app.

First of all, we wait for some action in the ofType.

RxJS operators

Later we use switchMap operator.

I prefer to use switchMap which returns an ‘inner’ Observable and stops emitting items from the earlier-emitted inner Observable and begins emitting items from the new one.

For instance, if async action calls several times ‘switchMap’ cancel a subscription to the previous async action call and wait for the result of the latest one.

Inside “switchMap” you can get access to the action payload if it provided.

As mentioned previously “switchMap” returns an inner Observable, for instance, promise.

From the inner observable you create a separate pipe to handle async action result.

First of all, I would like to pay attention to the “startWith” operator to set pending action from the start.

For the success, handling I prefer to use “flatMap” which in general mining like a then in promises and catchError for the error handling.

Please, pay attention that all operators (startWith, flatMap and catchError) are inside “inner” Observable for handling async promise.

This is a very simple and easy way of reading to handle async actions.
And the latest thing, don’t forget to add an epic to the “combineEpics” from redux-observable.

Top comments (2)

joshpitzalis profile image

Why do you use .pipe twice? Why not handle the result of fromPromise(promise()) on the outer observable. If I understand correctly the point of switchMap and the other Map type operators is to merge the inner observable with the outer observable. In which case what is the advantage of processing the response from the process on the inner observable? Would it be cleaner to handle the sequence of events on the outer observable. I mean Isn't the whole point to try and avoid approaching callback hell? I'm just starting out with rxjs and responding to this query would be super helpful. Thank you for writing the article.

khizerrehandev profile image
khizerrehandev • Edited

What is the purpose of dispatching an action with startWith(ActionCreator()) ??