Integrating WebSocket with Redux-Saga via Event Channel
Showcase how to integrate WebSocket events into Redux-Saga using an event channel to handle real-time data updates.
import { eventChannel } from 'redux-saga';
import { take, call, put, fork } from 'redux-saga/effects';
import { websocketConnected, websocketDisconnected, newDataReceived } from './actions';
Imports necessary functions from redux-saga and action creators from an actions file.
function createWebSocketConnection() {
return new WebSocket('ws://your-websocket-url');
}
Function to create a new WebSocket connection to the given URL.
function createWebSocketChannel(socket) {
return eventChannel(emitter => {
socket.onopen = () => {
emitter(websocketConnected());
};
socket.onclose = () => {
emitter(websocketDisconnected());
emitter(END);
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
emitter(newDataReceived(data));
};
return () => {
socket.close();
};
});
}
Function to create a channel that listens to WebSocket events. It emits actions on open, close, and message events from the WebSocket.
function* listenForSocketMessages() {
const socket = yield call(createWebSocketConnection);
const socketChannel = yield call(createWebSocketChannel, socket);
try {
while (true) {
const action = yield take(socketChannel);
yield put(action);
}
} finally {
if (yield cancelled()) {
socketChannel.close();
}
}
}
Saga that initiates the WebSocket connection and listens for messages. It then dispatches the emitted actions into the Redux store.
function* rootSaga() {
yield fork(listenForSocketMessages);
}
Root saga to fork the WebSocket message listener saga. This setup allows the application to continue its execution without blocking.