RxJS - Create Observable from an EventEmitter's multiple events

余生颓废 提交于 2019-12-13 03:35:46

问题


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:


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


来源:https://stackoverflow.com/questions/48621655/rxjs-create-observable-from-an-eventemitters-multiple-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!