RXJS if with observable as conditional

后端 未结 2 488
后悔当初
后悔当初 2020-12-10 17:16

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

2条回答
  •  鱼传尺愫
    2020-12-10 17:43

    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.

提交回复
热议问题