Rxjs 只执行一次处理程序 [英] Rxjs execute the handler only once

查看:82
本文介绍了Rxjs 只执行一次处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个可观察对象,当其中一个被触发时,我也在使用合并运算符进行监听,或者两者我都只需要执行一次处理程序,我该如何使用 rx 执行此操作?

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'))

推荐答案

可以使用多播的选择器功能

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

这篇关于Rxjs 只执行一次处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆