30

Is it possible to model if/else control structures via RxJS operators. As far as I understood we could use Observable.filter() to simulate an IF branch, but I am not sure if we simulate an ELSE branch via any of the Observable operator.

2

1 Answer 1

50

There are a couple operators that you could use to emulate this:

In order from most likely what you are asking for

partition

//Returns an array containing two Observables
//One whose elements pass the filter, and another whose elements don't

var items = observableSource.partition((x) => x % 2 == 0);

var evens = items[0];
var odds = items[1];

//Only even numbers
evens.subscribe();

//Only odd numbers
odds.subscribe();

// Using RxJS >= 6
const [evens, odds] = partition(observableSource, x => x % 2 == 0);

//Only even numbers
evens.subscribe();

//Only odd numbers
odds.subscribe();

groupBy

//Uses a key selector and equality comparer to generate an Observable of GroupedObservables
observableSource.groupBy((value) => value % 2, (value) => value)
  .subscribe(groupedObservable => {
    groupedObservable.subscribe(groupedObservable.key ? oddObserver : evenObserver);
  });

if edit renamed to iif in v6

//Propagates one of the sources based on a particular condition
//!!Only one Observable will be subscribed to!!
Rx.Observable.if(() => value > 5, Rx.Observable.just(5), Rx.Observable.from([1,2, 3]))

// Using RxJS >= 6
iif(() => value > 5, of(5), from([1, 2, 3]))

case (Only available in RxJS 4)

//Similar to `if` but it takes an object and only propagates based on key matching
//It takes an optional argument if none of the items match
//!!Only one Observable will be subscribed to!!
Rx.Observable.case(() => "blah",
{
  blah : //..Observable,
  foo : //..Another Observable,
  bar : //..Yet another
}, Rx.Observable.throw("Should have matched!"))
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for providing this comprehensive list of operators. I guess depending on use case I can use one of these operators to simulate if/else. For my particular example Rx.Observable.if() did the trick.
Tons more operators/details at the rxjs docs: github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/…
Thanks for all the details. Rx.Observable.if() with elseSource did the trick.
Despite it being nowhere to be found in the docs, Observable.if is in fact available in RxJs 5.
@paulpdaniels how does the groupby works if we're using hot observable ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.