How to use RxJs with Socket.IO on event

后端 未结 6 910
温柔的废话
温柔的废话 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:28

    You can use rxjs-dom,

    Rx.DOM.fromWebSocket(url, protocol, [openObserver], [closeObserver])
    
    
    // an observer for when the socket is open
    var openObserver = Rx.Observer.create(function(e) {
      console.info('socket open');
    
      // Now it is safe to send a message
      socket.onNext('test');
    });
    
    // an observer for when the socket is about to close
    var closingObserver = Rx.Observer.create(function() {
      console.log('socket is about to close');
    });
    
    // create a web socket subject
    socket = Rx.DOM.fromWebSocket(
      'ws://echo.websocket.org',
      null, // no protocol
      openObserver,
      closingObserver);
    
    // subscribing creates the underlying socket and will emit a stream of incoming
    // message events
    socket.subscribe(
      function(e) {
        console.log('message: %s', e.data);
      },
      function(e) {
        // errors and "unclean" closes land here
        console.error('error: %s', e);
      },
      function() {
        // the socket has been closed
        console.info('socket closed');
      }
    );
    

提交回复
热议问题