7

When using reactive frameworks I have seen both solutions below to make a mutually exclusive selection of which stream will be forwarded (rxjava in this case)

Observable.merge(
  Observable.just(aBoolStatement).filter(aBoolean -> aBoolean).flatMap(aBoolean -> signal1),
  Observable.just(aBoolStatement).filter(aBoolean -> !aBoolean).flatMap(aBoolean -> signal2)      
)

-

Observable.just(aBoolStatement).flatMap(aBoolean -> {
  if(aBoolean)
    return signal1
  else
    return signal2
}

The first code is all rx which is nice but it also evaluates the statement twice which is easy to miss if you would ever need to update the statement. Is there a preferred way of doing this or any other way to achieve the same result?

3
  • 4
    What does "rx" mean? Commented Dec 3, 2015 at 14:09
  • reactive extension I think Commented Dec 4, 2015 at 7:00
  • @ErikJohansson Yes :)
    – milosmns
    Commented Jul 20, 2018 at 13:04

1 Answer 1

8

This probably depends heavily on your input size, but the first example is definitely doing more unnecessary work. It has to filter the input twice, and then merge it all back together. The second example gets it all in one pass.

Also, the second can be written as a fairly elegant one-liner (assuming this is Scala, which it appears to be)

Observable.just(aBoolStatement).flatMap(b -> if(b) signal1 else signal2)

This is due to the fact that if is an expression that returns a value in Scala, so including the return keyword on each branch is redundant. Using if like this is equivalent to using a ternary expression (b ? signal1 : signal2) in another language that supports that syntax.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.