DEV Community

Mariappan S
Mariappan S

Posted on

Reactive Programming

Well, you heard it right? I’m here talking about one of those fancy programming terms which you might have clocked many a time, yet a stranger (un)fortunately. If so, I’ll try to break my learnings and introduce the paradigm in a simple practical way as possible.

It took me some time to grasp good references talking about reactive programming in general. There were tons of RxJS articles but those didn’t relate much until I read about reactive programming in general. If you’re someone tired of frameworks and looking to recharge yourself this could excite you. Let’s dive in!

So what is reactive in general?

Have you ever been excited about an upcoming mobile phone launch on some e-commerce sites? Or let’s say you’re a bike enthusiast you might be having an eye on some upcoming superbike launch, right? In this online world, it’s so easier to stay updated with these launches. If you’ve been to those companies' online stores, probably you’d find a NOTIFY ME trigger somewhere on the product page. I was looking for a smart band and landed at the official Xiaomi site — tada, this splashed up.

Image description

When you click on this notify button, they might take your mobile number/email and notify you on launch. Let’s think of this flow.

Technically, you’re subscribing to an event and the responsible entity is notifying you of the successful event. Probably once notified you would take some decision. That’s simple, isn’t it reactive? You’re reacting to an event.

Let’s discuss one more edge case to explore a different dimension of this. I’m looking to buy a smartphone at amazon.com and it’s currently out of stock. Luckily, Amazon provides me a way to get notified of the product once the item is back in stock. I’m subscribing to it, so as others with similar interests. Of course, I may not be the single user waiting for the stock right? So let’s say, myself and 9 others subscribed to get notified when stock is back. After some days, there were 3 items back in stock. All 10 of us will get notified. Cool, let’s say 3 of us immediately reacted (well, we’re too reactive 👊) and what would be the case. The item would go again out of stock. Here, the system needs to handle 2 things,

  • It should unsubscribe 3 of us who actually brought the phones should not be notified from now on
  • Since, it’s again out of stock, the remaining 7 should be notified of it and put back in listening mode 😔

Here if you notice, the system (producer) is unaware of certain details like whether the item would go out of stock again. If so how fast. It just reacts to the events, right?

That’s the deal, how did I go? 🏄

Little, little, let’s add some javascript to it

Directly spicing with some code, blink over it for a while 👀

Image description

If you check the above code, why do you think Leena’s salary is not being updated? Did the boss cheat her (or) JS is lying 😆

This is how typically Javascript works right? Loving it 🙋

To solve this, you’ve to repeat the totalSalary calculation again. But, it’s unfair right — I’m literally repeating the same statement every time I’m updating the value. You’d say, introduce a function calculateSalary and reuse it. Even in that case, I’d repeat the function call again :)

Here is where reactive programming comes into the picture. Well, I’m not going to write any RxJS code here now. Instead, let’s talk with some pictures.

Image description

To break the above diagram,

The system has 2 components — salary and payslip

Whenever there is a change in the salary component, payslip get’s updated. Here,

Salary component — is the producer
Payslip components — is the subscriber

And, interesting thing to note here, payslip is reactive on the salary changes and does it job. But, the salary component is unaware that the payslip component is dependent of it. That’s the beauty of this paradigm.

What next?

Are you still with me? Then one thing must be clear to you now having explored the possibilities and use cases above.

  • Reactive programming is no more a trend, and this could be the time to adopt

Does Javascript provide us with any native APIs to write reactive code?

Well, the answer is surprisingly no. But, there is an active tc39 proposal going on around for a while, didn’t find it much active though, you could watch out here — https://github.com/tc39/proposal-observable

Now comes the next question. What are observables?

The entity which can be used for reactive code and also can produce multiple values synchronously or asynchronously is called Observables.

I know that doesn’t sound cool enough. To understand this better, we need to explore a few other terms conjointly.

Streams

Basically, reactive programming gives you the ability to create data streams of anything.

So what are streams?

Anything can be a stream, variables, user inputs, properties, caches, data structure, etc.To be specific,

A stream is a sequence of ongoing events ordered in time. It can emit 3 possible things,

  1. Value (of some type)
  2. Error (something wrong happened)
  3. Completed signal (when the stream is done or completed)

Image description

Subscribe — listening to the stream is called subscribing

Thus, The functions that we are defining to deal with the ongoing events are called observers. Makes sense, now?

Observable will call the Observer’s next(value) method to trigger notifications, if things go well Observable will call an Observer’s complete() method exactly once. Else the Observer’s error(err) method exactly once.

Then what is RxJS?

As discussed above Javascript doesn’t have observables. There are external libraries that fill this gap and the most famous one is RxJs. It is a reactive extension for JavaScript which provides observables along with many other handy features.

Do you know chances are high that you’ve already used reactive programming? Know how?

If you have used any modern frameworks such as ReactJS, Angular, Vue, Svelte, etc. you have already written a lot of reactive programming. For eg: In react/Vue you would be updating a state and the view renders with the updated value, right? Imaging, how hectic & costlier it would be in older days when one would query the DOM, modify it and update it manually using innerHTML for god sake 😟

Thus to conclude your favorite frameworks in JavaScript have adopted reactive programming at their core and you might not even have realized that you have written tones of reactive code being a frontend developer 😄

Investing in Reactive paradigm

Reactive programming has enabled web developers to produce features faster by providing them with the ability to compose complex tasks with ease. Reactive programming is already enabling our lives to be better by powering products built by Netflix, Slack, Microsoft, Facebook, and many more. The more we understand it, the more productive web can be built around it. We got a reason to stay excited and why not?

References:

If you have any suggestions (as I’m new to this) or wish to discuss more on this topic please write to me at mariappangameo@gmail.com. I’d also love to connect with you all on Linkedin.

Top comments (0)