23

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 RxJS. Here is my problem.

I have a distSensor.js that has a function pingEnd()

function pingEnd(x){
socket.emit("sense", dist); //pingEnd is fired when an Interrupt is generated.
}

Inside my App.js I have

io.on('connection', function (socket) {
    socket.on('sense', function (data) {
        //console.log('sense from App4 was called ' + data);
    });
});

The sense function gets lots of sensor data which I want to filter using RxJS and I don't know what should I do next to use RxJs here. Any pointers to right docs or sample would help.

Mitul
  • 9,734
  • 4
  • 43
  • 60

6 Answers6

19

You can use Rx.Observable.fromEvent (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/fromevent.md).

Here's how I did a similar thing using Bacon.js, which has a very similar API: https://github.com/raimohanska/bacon-minsk-2015/blob/gh-pages/server.js#L13

So in Bacon.js it would go like

io.on('connection', function(socket){
  Bacon.fromEvent(socket, "sense")
    .filter(function(data) { return true })
    .forEach(function(data) { dealWith(data) })
})

And in RxJs you'd replace Bacon.fromEvent with Rx.Observable.fromEvent.

j0131n
  • 63
  • 1
  • 3
raimohanska
  • 3,265
  • 17
  • 28
  • 5
    Please remove the "i think" because it works fine. Also replace Bacon with `Rx.Observable` as you discribed already. – Mick Jan 20 '18 at 00:25
19

I have experienced some strange issues using the fromEvent method, so I prefer just to create my own Observable:

function RxfromIO (io, eventName) {
  return Rx.Observable.create(observer => {
    io.on(eventName, (data) => {
        observer.onNext(data)
    });
    return {
        dispose : io.close
    }
});

I can then use like this:

let $connection = RxfromIO(io, 'connection');
Morten Poulsen
  • 1,163
  • 1
  • 8
  • 9
10

You can create an Observable like so:

var senses = Rx.Observable.fromEventPattern(
    function add (h) {
      socket.on('sense',h);
    }
  );

Then use senses like any other Observable.

Xesued
  • 4,147
  • 2
  • 25
  • 18
  • What is the function of add(h) method? Is that function part of RxJs? – Mitul Apr 23 '15 at 13:17
  • 1
    I'm just naming the function, you just do: `function(h){...}`. – Xesued Apr 24 '15 at 17:31
  • fromEvent didnt work for me. And I ended up with this solution instead. In TS its: `let obs = Observable.fromEventPattern(h => this.socket.on('my_event', h));` – DarkNeuron Feb 07 '17 at 13:59
  • 3
    Just use fromEvent no need to write this extra code! `const sense$ = Rx.Observable.fromEvent(socket, 'sense');` – Mick Jan 20 '18 at 00:24
4

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);
Mick
  • 8,203
  • 10
  • 44
  • 66
  • 2
    Hello @Mick, excellent sample, but how about client side? I'm struggling with how disconnect when the unsubscribe is called over the fromEvent observable. – Bernardo Baumblatt Mar 29 '19 at 16:59
1

ES6 one liner that i use, using ES7 bind syntax:
(read $ as stream)

import { Observable } from 'rxjs'

// create socket

const message$ = Observable.create($ => socket.on('message', ::$.next))
// translates to: Observable.create($ => socket.on('message', $.next.bind(this)))

// filter example
const subscription = message$
  .filter(message => message.text !== 'spam')
  //or .filter(({ text }) => text !== 'spam')
  .subscribe(::console.log)
woudsma
  • 129
  • 2
  • 4
0

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');
  }
);
serkan
  • 6,885
  • 4
  • 41
  • 49
  • It seems that Rx.DOM.fromWebSocket can't use with socket.io-server. Rx.DOM.fromWebSocket use w3c standard websocket API. – clark Jul 20 '17 at 04:17