问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/40500658/should-we-create-one-epic-per-action-type-in-redux-observable