Blog>
Snippets

Broadcasting Actions with multicastChannel

Setup a multicastChannel to distribute the same action to multiple sagas and handle them simultaneously.
import { multicastChannel } from 'redux-saga';
import { take, call, put, fork } from 'redux-saga/effects';
Imports required functions from redux-saga.
function* watchRequests() {
  const channel = yield call(multicastChannel);
  // Fork different workers
  yield fork(logWorker, channel);
  yield fork(mainWorker, channel);

  while (true) {
    const { payload } = yield take('REQUEST');
    // Put payload on the channel to be consumed by worker sagas
    yield put(channel, payload);
  }
}
Creates a channel to distribute incoming requests and forks worker sagas to handle these requests.
function* logWorker(channel) {
  while (true) {
    const payload = yield take(channel);
    console.log('logWorker:', payload);
  }
}
Defines a logWorker saga that logs the payload taken from the channel.
function* mainWorker(channel) {
  while (true) {
    const payload = yield take(channel);
    console.log('mainWorker', payload);
    // Handle the request
  }
}
Defines a mainWorker saga to process the payload taken from the channel.