RXJS如果具有可观察的条件 [英] RXJS if with observable as conditional

查看:170
本文介绍了RXJS如果具有可观察的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果条件observable解析为true或false,我想使用 Rx.Observable.if 来运行两个observable中的一个。

I want to use Rx.Observable.if to run one of two observables should a conditional observable resolve to true or false.

我想要达到的目标如下:

What I want to achieve would look something like this:

Rx.Observable.if(conditionalObservable.map(x => x.length > 0), firstObservable, secondObservable).subscribe()

如果 conditionalObservable 发送一个next,然后使用true值完成,则应运行 firstObservable ,否则, secondObservable 应该运行。

If conditionalObservable sends a next and then completes with a true value, firstObservable should be run and otherwise, secondObservable should run.

现在显然这不起作用,因为 Rx.Observable.if 期望函数是有条件的,而不是可观察的。如何在RXJS中实现完全相同的功能?

Now obviously that doesn't work because Rx.Observable.if expects a function conditional, not an observable. How can I achieve the exact same functionality in RXJS?

注意:这个问题几乎相同,但我认为它不够简洁,因为1)你必须有两个可用的语句和2)除非你将 take(1)附加到条件可观察量,否则你不能保证条件不会发出更多的下一个事件。 IMO这是一种解决方法,并且更容易出现人为错误。

Note: This issue is almost the same but I don't think it's concise enough because 1) you have to have two pausable statements and 2) unless you append a take(1) to your conditional observables, you can't guarantee the conditional won't emit more next events. IMO it's a workaround and subject to much more human error.

推荐答案

如果我理解得很好,你可以尝试这样的事情:

If I understand well, you could try something like that:

conditionalObservable.map(x => x.length > 0)
  .last()
  .flatMap(function(condition){
      return condition ? firstObservable : secondObservable});
  .subscribe()

我添加了 last part因为您提到要在 conditionalObservable 最后一个值上选择您的observable(第一个或第二个)。

I added the last part because you mentioned that you want to choose your observable (first or second) on the conditionalObservable last value.

我不确定 if 运算符的值,因为它根据标量值切换必须由选择器功能同步生成。因此,除非您使用该函数返回一个可在闭包中访问的变量,并且您可以在评估条件的位置进行修改,但在我看来它并不是那么有用。即使这样,你的选择器也会变成一个不纯的函数,这不是测试目的的最佳实践。

I am not sure of the value of the if operator here, as it switches based on a scalar value which has to be produced synchronously by the selector function. So unless you use that function to return a variable which is accessible in a closure, and which you can modify at the point where your condition is evaluated, it is not so useful in my opinion. And even then, your selector becomes an impure function which is not a best practice for testing purposes and else.

这篇关于RXJS如果具有可观察的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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