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.
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.