Rather than having both run independently, you can call or fork the dependent generator from the initial one after the necessary logic has been performed.
Note there is a subtle but important difference between call
and fork
. call(saga2)
is blocking so would pause your while loop and not react to any more "MY_ACTION"
actions until saga2 has completed too, whereas fork(saga2)
is non-blocking, acting like a background task so would continue to execute in parallel to your loop resuming, so you could continue to respond to further "MY_ACTION"
.
Another thing to note is that fork
is still attached to the parent saga, so will be cancelled along with it, errors will bubble to parent from it etc. I imagine this is desirable but if you need a completely detached version that will continue to run no matter what happens to parent saga, use spawn
instead
function* rootSaga() {
yield all([
fork(saga1)
])
}
function* saga1() {
while (true) {
//Random logic
const action = yield take("MY_ACTION")
//Finish executing logic
// BLOCKING `call` saga2, passing original action as param if needed
yield call(saga2, action)
// OR NON-BLOCKING `fork` saga2
yield fork(saga2, action)
// OR NON-BLOCKING DETACHED `spawn` saga2
yield spawn(saga2, action)
}
}
function* saga2(action) {
// Do whatever dependant logic
// safe in the knowledge that saga1 has done its job already
}