Blog>
Snippets

Handling Channel Closure and Cleanup

Provide an example of how to properly close channels and clean up in sagas to prevent memory leaks.
import { eventChannel, END } from 'redux-saga';
import { take, call, put, cancelled } from 'redux-saga/effects';

function createEventChannel() {
  return eventChannel(emitter => {
    const interval = setInterval(() => {
      emitter(new Date()); // Emitting current date/time
    }, 1000);

    // Cleanup function
    return () => {
      clearInterval(interval);
      console.log('Channel closed and cleaned up.');
    };
  });
}
Creates an event channel that emits the current date/time every second. The return function cleans up by clearing the interval when the channel is closed.
export function* mySaga() {
  const chan = yield call(createEventChannel);
  try {
    while (true) {
      const data = yield take(chan);
      console.log('Received from channel:', data);
    }
  } finally {
    if (yield cancelled()) {
      console.log('Saga was cancelled, closing channel.');
      chan.close();
    }
  }
}
Defines a saga that subscribes to the event channel. It logs data received from the channel. If the saga gets cancelled, it will clean up by closing the channel in the finally block.