How to use RxJs with Socket.IO on event

后端 未结 6 895
温柔的废话
温柔的废话 2021-02-02 12:56

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

6条回答
  •  北海茫月
    2021-02-02 13:18

    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);
    

提交回复
热议问题