Blog>
Snippets

Implementing a Fixed Buffer in Saga Channel

Illustrate the use of a fixed buffer in a Redux-Saga channel to control the flow of incoming actions, ensuring that the channel only keeps a set number of messages and discards the rest.
import { buffers } from 'redux-saga';
import { actionChannel, take, call } from 'redux-saga/effects';

function* mySaga() {
  // Using a fixed buffer
  const buffer = buffers.fixed(5); // Buffer size of 5 actions
  const chan = yield actionChannel('MY_ACTION', buffer);

  while (true) {
    // Taking action from the channel
    const action = yield take(chan);
    // Handling the action
    yield call(handleAction, action);
  }
}

function* handleAction(action) {
  // Process the action
  console.log('Handling action', action);
}
This example demonstrates how to use a fixed buffer with a Redux-Saga channel to handle 'MY_ACTION' actions. Here, 'buffers.fixed(5)' creates a buffer that holds a maximum of 5 actions. Any additional actions dispatched to the channel are discarded if the buffer is full. The 'actionChannel' watches for 'MY_ACTION' and queues them in the buffer. The 'while (true)' loop continuously takes actions from the channel and processes them with 'handleAction', ensuring that only up to 5 actions are queued at any time.