Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
scroll top