So, you’ve heard about reactive programming.
Then you got discouraged, almost immediately.
Like: is this guy really talking about switching on the observable of observables? I have no idea what’s going on.
That’s all fine, we agree on one thing: people usually try to explain functional programming in a way that only makes sense to people who already know functional programming.
Let me show you something, maybe it can help with your appetite.
Have you heard of pipes? streams? signals? observables? eventemitters?
Let’s imagine they’re all the same: channels that emit events, over time.
And just in this moment, your boss interrupts you.
She asks you to implement a new feature in the app. She gives you this brief:
When the user starts simultaneously panning and rotating an object, start a countdown from 3. Stop the timer either when the countdown ends or when the user stops the gestures.
This is gonna be a mission critical part of the app. There’s no way you can make a mistake here.
So, as an imperative programmer, you start thinking about what do you need to keep track of in order to implement this:
“user starts simultaneously panning and rotating an object” - okay, I need to store this in a variable.
I mean, otherwise how else can I check if both of them happening at the same time?
“Stop the timer either when the countdown ends” - means I’ll need to keep track of the timer. And also, the number of seconds left.
So, you get the idea: we’re building a kind-of data structure describing what’s exactly happening at the screen, in this specific moment, so we can compare the old state with the new state - this is how we’re building our control-flow.
So, we turned our original sentence into this:
Ohh my god, it involves having 4 temporarily variables expressing the state of the UI!
Also, it is nothing like the original English sentence. The logic is buried between if statements, where we set random booleans.
We write functions to eliminate duplicated code. And the we jump around like an inconsistent bugs bunny - there are 5 of them, all calling each other.
How can we improve upon this?
So, the question that reactive programming can help you with is:
How can you replace all those “if” instances with “when”?
Let’s have a look!
And now, voila, all four of the temporary variables are gone!
Also, did you notice, that the code looks like this:
You can also compress the syntax quite a bit, if you want to see how, here’s the link to the file!
Have a look at the example project here and feel free to play around.