RXJS if with observable conditional

I want to use Rx.Observable.ifone of the two observables to start if the conditional observable solution is true or false.

What I want to achieve will look something like this:

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

If it conditionalObservablesends the following, and then completes with a true value, it firstObservablemust be executed, otherwise it secondObservablemust be executed.

Now it’s obvious that this does not work because it Rx.Observable.ifexpects a conditional function, not an observable one. How can I achieve the same functionality in RXJS?

Note: This problem is almost the same, but I don’t think it is compressed enough, because 1) you must have two statements pausableand 2) if you add take(1)to your conditional observables you cannot guarantee that the condition will not generate more of the following events. IMO is a workaround and is subject to much larger human error.

+4
source share
2 answers

If I understand well, you can try something like this:

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

I added a part lastbecause you mentioned that you want to select your observable (first or second) in the last value conditionalObservable.

if , , . , , , , , , . , , .

+2

switch?

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

flatMapLatest? , , :

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

Source: https://habr.com/ru/post/1623816/


All Articles