Using Standard Channel for Inter-Saga Communication
Demonstrate the creation of a standard channel using `channel()` from Redux-Saga, then illustrate sending and receiving messages between sagas to coordinate activities or data exchange.
import { channel } from 'redux-saga';
import { take, put, call } from 'redux-saga/effects';
Imports required functions from redux-saga.
function* sagaOne(chan) {
while (true) {
const action = yield take(chan);
// Process the incoming action
console.log('Saga One received action', action);
}
}
Defines a saga that listens for actions from a channel. It logs any action it receives.
function* sagaTwo(chan) {
while (true) {
// Simulate sending an action
yield call(
() => new Promise(resolve => setTimeout(() => resolve({ type: 'ACTION_FROM_SAGA_TWO' }), 1000))
);
yield put(chan, { type: 'ACTION_FROM_SAGA_TWO' });
console.log('Saga Two sent an action');
}
}
Defines another saga that periodically sends actions into the channel. It simulates an async operation before sending the action.
function* rootSaga() {
const chan = yield call(channel);
yield call(sagaOne, chan);
yield call(sagaTwo, chan);
}
Sets up the root saga. It creates a channel and starts both sagaOne and sagaTwo, providing them with the channel for communication.