How to create rootSaga?
According to a core developer of redux-saga [1,2] the idiomatic way to create rootSaga is to use the all Effect Combinator. Also, please note that yielding arrays from sagas is deprecated.
Example 1
You could use something like this (+all)
import { fork, all } from 'redux-saga/effects';
import firstSaga from './firstSaga';
import secondSaga from './secondSaga';
import thirdSaga from './thirdSaga';
export default function* rootSaga() {
yield all([
fork(firstSaga),
fork(secondSaga),
fork(thirdSaga),
]);
}
Example 2
Taken from here
// foo.js
import { takeEvery } from 'redux-saga/effects';
export const fooSagas = [
takeEvery("FOO_A", fooASaga),
takeEvery("FOO_B", fooBSaga),
]
// bar.js
import { takeEvery } from 'redux-saga/effects';
export const barSagas = [
takeEvery("BAR_A", barASaga),
takeEvery("BAR_B", barBSaga),
];
// index.js
import { fooSagas } from './foo';
import { barSagas } from './bar';
export default function* rootSaga() {
yield all([
...fooSagas,
...barSagas
])
}
fork vs. spawn
fork and spawn will both return Task objects. Forked tasks are attached to parent, whereas spawned tasks are detached from the parent.
-
Error handling in forks https://stackoverflow.com/questions/39438005/what-is-the-idiomatic-way-of-starting-rootsaga:
Errors from child tasks automatically bubble up to their parents. If
any forked task raises an uncaught error, then the parent task will
abort with the child Error, and the whole Parent’s execution tree
(i.e. forked tasks + the main task represented by the parent’s body if
it’s still running) will be cancelled. -
Error handling in spawned tasks https://stackoverflow.com/questions/39438005/what-is-the-idiomatic-way-of-starting-rootsaga:
The parent will not wait for detached tasks to terminate before returning and all events which may affect the parent or the detached task are completely independent (error, cancellation).
Based on above, you could, use fork for “mission critical” tasks, i.e. “if this task fails, please crash the whole app”, and spawn for “not critical” tasks, i.e. “if this task fails, do not propagate the error to the parent”.