Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we create one Epic per action type? in redux-observable

I am in process of redux-observable learning, and I have some doubts:

Should we create an Epic for each action to watch?

export const actionEpic = action $ => action$.ofType('ACTION')
export const action2Epic = action $ => action$.ofType('ACTION2')

Or can we create it for many like reducers with switch? import every single Epic to convine in the middleware is a lot of work

like image 637
MatCas Avatar asked Nov 09 '16 05:11

MatCas


People also ask

What are Redux epics?

An Epic is the core primitive of redux-observable. It is a function which takes a stream of actions and returns a stream of actions. Actions in, actions out.

What is observable action?

Observable data actions are used to track the status of a data action as it's running. This capability is helpful if you must run logic or render a user interface (UI) in response to the current status of a data action. Observable data actions use a special promise-like class that is named AsyncResult.

Does Redux use observable?

Redux Observables In Redux, whenever an action is dispatched, it runs through all the reducer functions and a new state is returned. Redux-observable takes all these dispatched actions and new states and creates two observables out of it - Actions observable action$ , and States observable state$ .

Can RxJS replace redux?

RxJS can be used to do Reactive Programming and is a very thorough library with 250+ operators. And Redux is as described on the github repo "Redux is a predictable state container for JavaScript apps". Redux is just a tool to handle state in apps. But in comparison you could build a full app in just RxJS.


1 Answers

A large majority of epics will begin by matching a single action, e.g. action$.ofType(SOMETHING). This is because usually these actions trigger some side effect (like an AJAX call) that is specific to a single task.

Think of something like fetching a user's model. You usually will only want to listen for FETCH_USER to start this process, but certainly that same epic may listen to other actions to know when to cancel in-flight requests, or similar.

If you mix side effect concerns in a single epic, like create one that handles both fetching the user and fetching a user's posts, you start to make your epics harder to maintain and test.

All of that said, there are no rules. There are legit (but rare) cases for an epic listening to multiple actions to begin some side effect. e.g. if an epic handles some generic task that applies to multiple domains, logging being the most obvious but there are others.

Just like reducers, multiple epics can listen for the same action, however this only makes sense when there is little-to-no coordination required between them.

like image 135
jayphelps Avatar answered Oct 17 '22 23:10

jayphelps