RxJS - Create Observable from an EventEmitter'

2019-08-16 16:10发布

I have a node.js EventEmitter which raises the following events: error, message.

Is there a straight forward way I can create an RxJS Observable from it?

i.e next() called on message and error() called on error.

1条回答
相关推荐>>
2楼-- · 2019-08-16 16:38

You can create it like this:

const obs$ = Observable.create(observer => {
  emitter.on('message', val => observer.next(val));
  emitter.on('error', err => observer.error(err));
});

As an alternative, you can do this by constructinng and chaining observables like this, but it's clearly less readable:

const message$ = Observable.fromEvent(emitter, 'message');
const error$ = Observable.fromEvent(emitter, 'error');

const obs$ = Observable.merge(
  message$.catch(err => Observable.of(err)),
  error$.mergeMap(val => Observable.throw(val)),
);
查看更多
登录 后发表回答