RxJS 订阅有两个参数 [英] RxJS Subscribe with two arguments

查看:32
本文介绍了RxJS 订阅有两个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个可观察对象,我想将它们组合起来,并在订阅中使用两个参数或仅使用一个.我尝试了 .ForkJoin、.merge、.concat,但无法实现我正在寻找的行为.

I have two observables which I want to combine and in subscribe use either both arguments or only one. I tried .ForkJoin, .merge, .concat but could not achieve the behaviour I'm looking for.

示例:

obs1: Observable<int>;
obs2: Observable<Boolean>;

save(): Observable<any> {
   return obs1.concat(obs2);
}

那么当使用这个函数时:

Then when using this function:

service.save().subscribe((first, second) => {
    console.log(first); // int e.g. 1000
    console.log(second); // Boolean, e.g. true
});

service.save().subscribe((first) => {
    console.log(first); // int e.g. 1000
});

是否有可能获得这种行为?

Is there a possibility to get exactly that behaviour?

希望有人能帮忙!

在我的特定用例中 obs1obs2 是两个不同的 post 请求:obs1 是实际保存函数和 obs2 检查是否有其他服务正在运行.

In my specific use case obs1<int> and obs2<bool> are two different post requests: obs1<int> is the actual save function and obs2<bool> checks if an other service is running.

obs1 的值需要在请求完成后重新加载页面,并且 obs2 的值需要在以下情况下显示消息服务正在运行 - 独立于 obs1.

The value of obs1<int> is needed to reload the page once the request is completed and the value of obs2<bool> is needed to display a message if the service is running - independant of obs1<int>.

因此,如果 obs2obs1 之前发出,那不是问题,消息会在重新加载之前显示.但是如果 obs1obs2 之前发出,页面会重新加载并且消息可能不再显示.

So if obs2<bool> emits before obs1<int>, that's not a problem, the message gets display before reload. But if obs1<int> emits before obs2<bool>, the page gets reloaded and the message may not be displayed anymore.

我之所以这么说是因为对于给定的答案,无论值是在其他 observable 的 onComplete 之前还是之后发出,都会有不同的行为,这会影响用例.

I'm telling this because with the given answers there are different behaviours whether the values get emitted before or after onComplete of the other observable and this can impact the use case.

推荐答案

您可以使用 forkJoin 用于此目的.并行调用它们,然后如果它们中的任何一个存在,则执行某些操作.

You can use forkJoin for this purpose. Call them parallely and then if either of them is present then do something.

let numberSource = Rx.Observable.of(100);
let booleanSource = Rx.Observable.of(true);

Rx.Observable.forkJoin(
  numberSource,
  booleanSource
).subscribe( ([numberResp, booleanResp]) => {
  if (numberResp) {
    console.log(numberResp);
    // do something
  } else if (booleanResp) {
    console.log(booleanResp);
    // do something
  }
});

这篇关于RxJS 订阅有两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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