RXJS if with observable as conditional

后端 未结 2 476
后悔当初
后悔当初 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.

    0 讨论(0)
  • 2020-12-10 17:49

    How about using switch?

    conditionalObservable
      .map(x => x.length > 0 ? firstObservable : secondObservable)
      .switch()
      .subscribe(...)
    

    Or flatMapLatest? If I understand the documentation well, this will do the same as the former:

    conditionalObservable
      .flatMapLatest(x => x.length > 0 ? firstObservable : secondObservable)
      .subscribe(...)
    
    0 讨论(0)
提交回复
热议问题