I want to use RxJS inside of my socket.on(\'sense\',function(data){});
. I am stuck and confused with very few documentation available and my lack of understanding R
Simply use fromEvent()
. Here is a full example in Node.js but works the same in browser. Note that i use first()
and takeUntil()
to prevent a memory leak: first()
only listens to one event and then completes. Now use takeUntil()
on all other socket-events you listen to so the observables complete on disconnect:
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const Rx = require('rxjs/Rx');
connection$ = Rx.Observable.fromEvent(io, 'connection');
connection$.subscribe(socket => {
console.log(`Client connected`);
// Observables
const disconnect$ = Rx.Observable.fromEvent(socket, 'disconnect').first();
const message$ = Rx.Observable.fromEvent(socket, 'message').takeUntil(disconnect$);
// Subscriptions
message$.subscribe(data => {
console.log(`Got message from client with data: ${data}`);
io.emit('message', data); // Emit to all clients
});
disconnect$.subscribe(() => {
console.log(`Client disconnected`);
})
});
server.listen(3000);