The ‘if’ in RxJS

To everybody who needs some logic…

David Ibl
2 min readJan 18, 2019
image by VanveenJF

There is no ‘if-else’ operator in RxJS??? WTF!

Finally, every algorithm needs some logic. When dealing with the reactive extensions the implementation of a very important use-case is not really obvious.

This article should tackle the question on how to write decision logic in a reactive implemented implementation without the need for further functions.

Whenever I review code in our very own codebase I see code implementing switches like this to fulfil requirements of reactive programming.

Map only ‘if (condition)’

Another way to implement decision logic in a reactive algorithm is the possibility to abstract the decision function. The code becomes way shorter. Readability won’t be increased by doing that.

‘toIf’ function. A shorter code and maybe some abstracted logic, but finally decreased readability in some cases.

What about an if-operator. And that is where things become interesting. When we think about an if operator which can be used seamlessly in our reactive algorithm we won’t find a real intuitive implementation for that.

That depends on the nature of the structure of a reactive algorithm. A reactive algorithm always shows us one flow.

The commands will be executed each after the each. That is always a linear algorithm. And because of that a condition always looks like some kind of foreign object in our algorithm.

But, let’s face the way it should look like.

When thinking about a conditional logic within a reactive algorithm, I’m sure many people will end up implementing something looking like that.

A bit like two inner pipes with different command chains. And that’s the point where things become interesting!

There is a way condition can be expressed in a reactive manner.

Finally, we are able to use a combination of filter and merge to express conditional flows with only on subscription.

We split the initial observable into two event streams. Each of those streams can have its very own commands. Those commands can do something really different. The first command stream will transform our async result in a totally different way than the other stream.

In the end, the merge command will join them together. One subscription can handle the output.

This implementation enables us to implement any logic in a reactive manner. There is no need for methods or functions hiding the command flow.

Even complex scenarios with many observables resulting in one subscription can be implemented in a really readable way.

--

--

David Ibl

Chief Platform Officer @lv1871 the fanciest assurance company