Reactive Programming basics [Updated 2020]

Reactive Programming basics [Updated 2020]

Like its name indicates, reactive programming is oriented to reaction, to the data flow and the principle of causality, meaning that, each cause is connected to its effects.

This is a paradigm, meaning that most problems that can be solved with reactive programming can also be solved by other types of programming; object-oriented, procedural, functional, etc. The most important thing is to recognize which approach is the most appropriate, because this decision impacts the elegance and the quality of the resolution obtained.

reactive programming

Like its name indicates, reactive programming is oriented to reaction, to the data flow and the principle of causality, meaning that, each cause is connected to its effects. Perhaps the most known example is the spreadsheets’ one; where the modification of a cell (event) triggers the following modification of all cells that were watching it. And “watching” is one of the keywords because it will be easier to understand the issue if we know the GoF observer’s pattern.

A little theory of Reactive Programming

The Manifesto of the reactive programming was rewritten at the end of 2014 and, according to it, the reactive systems have 4 features:

  • Responsiveness: They are focused on quick and consistent times of response. Error handling is simplified and encourages interaction with the user
  • Resilience: systems will remain responsive even in the presence of errors. For this to be achieved, failures should be isolated and contained in components and should be able to recover without compromising its integrity.
  • Elasticity: Because they adapt to variations in workload, allocating, and freeing resources dynamically, and because they are designed so that its components do not form bottlenecks.
  • Oriented messages: the exchange of asynchronous messages is completely trusted. Blocking communication doesn’t exist. The elasticity, faults, and messages are points to consider here.

The elasticity differs from scalability:  the program is not defined along with the resources; these are automatically allocated at runtime (very similar to functional programming).

Failures differ from mistakes: failure is unexpected and is not used as flow control. You can disable the part of the system that depends directly on these.

The messages differ from the events: in an event-based system, the components actively expect that entities change of state. Instead, the messages have an associated recipient that is activated when they are received.

Viewing data flows

To display the data, a marbles diagrams are often used. You can see in them each data stream and the underlying transactions that can be applied to them:

Reactive Programming

These diagrams are read from left to right, and each ball represents the occurrence of an event that is being observed. Intermediates rectangles indicate the operation to be applied to each. For example, in the image include the following:

• Map: It applies a transformation as a parameter passed to the emissions of a data stream.

• FlatMap: Make asynchronous applications to data flow, and then crushes emissions to a simple observable.

• Concat: concatenates emissions of two or more streams without crossing them (Note that the flows should “finish” to make it applicable).

• Merge: Combines multiple flows and interlocks emissions.

All these diagrams can be displayed interactively on this website. Can you guess what these two operations make? Operation1, Operation2.

Perhaps the trickiest part of programming is not reactive programming itself; how difficult is to think about the “how” to deal with common problems. For example, if I need an action to be triggered when a user performs multiple clicks on an item, the communication flow should be, approximately, as follows:

save 2

As you can see, there are no temporary variables, buffers, promises, active checks, or other traditional programming resources. Only flows, emissions, and four lines of code.

Environments and languages to use reactive programming

We can find languages specifically reactive as Elm and R. Most frameworks that have their reactive part are available for .NET and JavaScript. In JavaScript we can find MeteorJS, ProActJS, BaconJS, and React.

Perhaps the main exponent is Reactive Extensions, or simply ReactiveX Rx (all names represent the same thing). This is an API for asynchronous programming and reactive available for Java, JavaScript (+ Angular), C # (+ Unity), Ruby, Python, PHP, and others. In total there are 402 observable operations, each with its corresponding diagram of marbles.

Here is an example of integration with Angular, when searching for a page on Wikipedia:

 login$.pipe(
withLatestFrom(userProfile$),
first()
).subscribe(
([login, profile]) => {
this.loading = false;
console.log(login);
login.numberOfResourcesRows = profile.numberRowsResources;
login.redirectAfterLogin = profile.redirectLink;
this.loginService.setUser(login);
this.navigator.goToUserHomePage(login.redirectAfterLogin);
},
error => {
this.loading=false;
switch (error.status) {
case 511: msg = 'User and Password are not valid.';
break;
case 401: msg = 'The user ' + user + ' is not a member of the group.';
break;
case 503: msg = 'There was an error generating the security token.';
break;
default: msg = 'An internal error occurred. If the problem persist please contact your administrator.';
break; 
}
this.username.focus(); 
}
); 

getMobileVersion(url:string): Observable<MobileVersion[]> {
return this.http.get(url)
.map(response => {
const res: any = response;
return res.map(mobileVersion => {
return {
id: mobileVersion.id,
nombreVersion : mobileVersion.nombreVersion,
descripcion: mobileVersion.descripcion,
ultimaversion : mobileVersion.ultimaversion,
sistemaOperativo: mobileVersion.sistemaOperativo
};
});
})
.catch(error =>
observableThrowError(error.error || 'Server error')
);
}

CHECK OUT THE HAT’S BLOG

Comments?  Contact us for more information. We’ll quickly get back to you with the information you need.

SUBSCRIBE TO OUR NEWSLETTER