RXJS 如果以 observable 作为条件 [英] RXJS if with observable as conditional

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

问题描述

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

我想要实现的目标如下:

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

如果 conditionalObservable 发送一个 next 然后以真值完成,firstObservable 应该运行,否则,secondObservable 应该运行.>

现在显然这是行不通的,因为 Rx.Observable.if 需要一个有条件的函数,而不是一个可观察的函数.如何在 RXJS 中实现完全相同的功能?

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

解决方案

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

conditionalObservable.map(x => x.length > 0).最后的().flatMap(函数(条件){退货条件?firstObservable : secondObservable});.订阅()

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

我不确定此处 if 运算符的值,因为它基于必须由选择器函数同步生成的标量值进行切换.因此,除非您使用该函数返回一个可在闭包中访问的变量,并且您可以在评估条件时对其进行修改,否则在我看来它不是很有用.即便如此,您的选择器也会变成一个不纯的函数,这对于测试目的和其他目的来说不是最佳实践.

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

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

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?

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

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

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 如果以 observable 作为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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