Here is an article for the JavaScript Programmers that explains what Reactive Programming is. This is a transcript of a talk session by the author during Open Source India 2019 at NIMHANS Convention centre, Bengaluru.
Before understanding Reactive programming, we need to understand Asynchronous programming.
Asynchronous Programming
Below is an example of an asynchronous program in JavaScript,
setTimeout(function(){ console.log("Async!") }, 1000);
The setTimeout is a native javascript function where we call setTimeout, it executes some code and after a certain time, it prints the output on the console which is after 1 second in the above example.
In the meantime, lets us see how javascript does this? When we execute this function which is setTimeout. Javascript doesn’t keep quiet for a second, it goes and does some other jobs like button click actions, maybe some mouse moments happened so it has to react to those actions and after 1 second it comes back and executes the conslo.log. So this example shows how asynchronous programming works.
The above code snippet is an example of the callback function. In the callback, it executes the first half of the program and it executes the later half of the program after a certain time interval. The callback is one of the patterns in asynchronous of the program. There are more asynchronous patterns like promises which are pretty popular. The callback was there for a lot of applications and used for decades. Now, promises came, why promises came? What was the problem with a callback? The callback was having a problem with trust issues. In the above example, the setTimeout is a method and we are passing a function to that means we are passing trust and then setTimeout decides after 1000 milliseconds what functions it should execute. Now let’s say that if we replace the setTimeout with some vendor function and we are passing something to the vendor function to get executed after a certain time interval means there is a trust issue. Consider two more vendors, a function which is there instead of calling it once, called five times. Let’s say it’s a retailer and your credit card got debited five times. So, that’s the issue of the callback. That is basically the trust issue which a “promise” resolves.
How does the promise work?
For example, you move to a coffee shop and then you say I need a cold coffee. What does a waiter do? He gives a slip, he didn’t give the cold coffee immediately and that slip is nothing but a promise to get a cold coffee after some time. We wait for some time and then we go back once our coffee is ready and we collect the coffee by submitting the slip back to the waiter. That exactly a promise works, we call a function like calling API, then javascript does its own stuff and whenever the promise returns I will get data and execute. That’s the fundamental difference between a callback and a promise. These are the two patterns of asynchronous. Then came the generators, These functions are a bit strange compared to normal functions. Once normal functions start execution then it only stops at the end of the line which is returned but the generator functions can stop in between the lines and are able to restart the whole function again after some point time. That asynchronous coding in a synchronous way using generators. The generators are also a pattern to do asynchronous programming. Then comes observables, which are mostly used with the current structure.
Let’s understand reactive programming
In an excel sheet consider four cells and one cell is input and all other cells are logically linked with the input cell. Now if you give the variable inputs to that particular input cell then the values of the other three cells will also be changed according to that input. Here this example explains how reactive programs work. How do we co-relate this with the javascript world? Reactive programming is pattern-oriented around data streams and the propagation of changes. That is exactly what is happening in the excel example. Once you link a logic behind the cells whenever the data is changed those changes will automatically be propagated in the cells.
Application of Reactive programming
Now let’s come to web application. In a typical web application we have a client, javascript code and we have backend services and everything happens against time. At the client-side some mouse click happens, some render happens, and a lot of events happen in web application and javascript code has to handle those events. The javascript code has to be already there to handle all the events continuously like button clicks events, render events and once the event occurs then the javascript code decides the actions based on those events like calling backend APIs and collecting data from APIs. All these events happen in a timely fashion this is what exactly a reactive pattern does. If the javascript code follows the reactive pattern then it is ready to handle those events and we don’t need to create a separate instance for each event. These events are nothing but data streams and we have a javascript code to propagate those changes. So now we got an idea of how reactive programming works and how it evolves from callbacks, promises and generators.
Now comes to a reactive extension to handle this. There is a library called a reactive extension which is nothing but an API for asynchronous programming in an observables pattern. An observable is nothing but a data stream. So, there are APIs to handle a continuous data stream in our application. Because when continuous events are happening obviously the javascript code is not waiting for a particular event to happen. It has to do a lot of things in the backend it may call an API and at the same time it has to execute the responses from API and then the event happens suddenly it has to react to that event. So, to handle these kinds of programming seamlessly we can use a reactive extension library. The reactive extension is a library from Microsoft and they have various versions like RxJava for Java programming, RxPython for python and RxJS, a JavaScript library of ReactiveX
ReactiveX is based on the observer pattern. Now what is an observer pattern? The observer pattern is a design pattern in which an object maintains a list of its dependents, called observers, and notifies them automatically of any state changes. Any time any event happens as button clicks render, etc we should have a javascript code to handle those events which we already know who all are observers for those events. For example, button click happens then the observer state changes now the javascript code call APIs based on the events.
Example observer code snippet for a button click event
Import { fromEvent } from 'rxjs'; var obsrv = fromEvent(button, 'click'); obsrv.subscribe(()=>{ console.log("Button Clicked !!"); });
In the above example there is a library rxjs we import formEvent from that library and we create an observer called obsrv that acts as an observer to the button. When the button is clicked then the observer subscribes will execute i.e console.log. This is how an exact way that observable pattern works in reactive programming. It is simple to execute this and the subscriber automatically calls when the button click happens.
Building Blocks of RxJS
1. Observables – a source data, we can create observables using RxJs
2. Operators- a method, two kinds of operator one is transforming your data and another operator for creating the observables like formEvent in above example
3. Subscription- is a function, can be used to subscribe or unsubscribe to that observable.
4. Subjects- it is a special kind of observer where multiple guys can subscribe to a single object observable one to one.
5. Scheduler- you can decide when you want to schedule your observables to emit the data.
These are the five building blocks of asynchronous programming using the RxJS library. It is widely popular in asynchronous programming and there are callbacks, promise by observable is super easy to implement.
Note: The talk session has been transcribed by Surya Teja of EFY editorial team.