Search code examples
node.jstypescriptrxjsjake

How can I change 'process.on' into RxJS style based events?


How can listen to NodeJS events with Rx?

I have the following code in my JakeJS file.

process.on("cmdStart", () => {
    console.log("> " + command)
});

and I want to do it in RxJS style but I'm not really sure what's the best way to do it.

I've read the docs and tried some of the examples they provide at github but I'm not quite sure, it doesn't seems to work, here is what I've tried.

const eventEmitter: any = new EventEmitter();

const cmdStart = Rx.Observable.fromEvent(eventEmitter, "cmdStart");

const subscription = cmdStart.subscribe(function (command) {
    console.log("> " + command)
});

eventEmitter.emit(command);

Solution

  • I've followed examples of RxJS doc (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/fromevent.md)

    var Rx = require('rx');
    var EventEmitter = require('events').EventEmitter;
    
    var eventEmitter = new EventEmitter();
    
    var source = Rx.Observable.fromEvent(eventEmitter, "cmdStart");
    source.subscribe(function (x) { console.log("> " + x) });
    eventEmitter.emit('cmdStart', 'testdata');