Rxjs execute the handler only once

对着背影说爱祢 提交于 2019-12-12 03:38:37

问题


I have two observable that I am listening too with the merge operator when one of them is fire, or both I need to execute the handler only once, How can I do this with rx?

var source1 = Rx.Observable.interval(1000);

var source2 = Rx.Observable.interval(1000);

var source = Rx.Observable.merge(
    source1,
    source2)
    .subscribe(() => console.log('This needs to run only once and not kill the stream'))

回答1:


You can use selector function of multicast

Optional selector function that can use the multicasted source stream as many times as needed, without causing multiple subscriptions to the source stream. Subscribers to the given source will receive all notifications of the source from the time of the subscription forward.

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-multicast

 function factory() {
   return new Rx.Subject();
 }

 source.multicast(factory, function(shared) {
   return shared.take(1).do(x=>console.log(x)).concat(shared);
 })
 .subscribe();


来源:https://stackoverflow.com/questions/43831736/rxjs-execute-the-handler-only-once

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