Reputation: 78
I'm trying to implement socket.io on my react/nodejs app. I can successfully subscribe for an event and push the data to the front end. But I couldn't un-subscribe from an event when it is no longer needed.
Version socket.io - 2.0.4 socket.io-client - 2.0.4
Below is the sample code
Frontend
subscribeForTimer() {
socket.on('timer', timestamp => {
console.log(timestamp)
});
socket.emit('subscribeToTimer', 1000);
}
UnubscribeFromTimer() {
socket.removeListener ( 'timer', (data) => {
console.log ( 'stopped' )
} );
}
Backend
const socketServer = http.createServer ();
// create a server instance with the port and host
socketServer.listen ( port, host );
// Make the sockets listen on the created server instance
const sio = io.listen ( socketServer );
sio.sockets.on ( socketEvents.CONNECTION, ( socket ) => {
subscribeToTimer ( socket );
UnubscribeFromTimer ( socket );
terminateConnection ( socket );
} );
function subscribeToTimer ( socket ) {
socket.on ( 'subscribeToTimer', ( interval ) => {
setInterval ( () => {
socket.emit ( 'timer', new Date () );
}, interval );
} );
}
I have tried using off/removeListener/removeAllListeners but nothing works. It doesn't throw any errors either. Any help is much appreciated. TIA!
Upvotes: 1
Views: 1743
Reputation: 5422
You should pass the same instance of the subscribed function to unsubscribe:
On frontend:
const subscribeFn = timestamp => {
console.log(timestamp)
}
subscribeForTimer() {
socket.on('timer', subscribeFn);
socket.emit('subscribeToTimer', 1000);
}
UnubscribeFromTimer() {
socket.removeListener('timer', subscribeFn);
}
on Backend
const socketServer = http.createServer ();
// create a server instance with the port and host
socketServer.listen ( port, host );
// Make the sockets listen on the created server instance
const sio = io.listen ( socketServer );
let intervalId;
sio.sockets.on ( socketEvents.CONNECTION, ( socket ) => {
subscribeToTimer ( socket );
intervalId && clearInterval(intervalId)
UnubscribeFromTimer ( socket );
terminateConnection ( socket );
} );
function subscribeToTimer ( socket ) {
socket.on ( 'subscribeToTimer', ( interval ) => {
intervalId = setInterval ( () => {
socket.emit ( 'timer', new Date () );
}, interval );
} );
}
Upvotes: 3