What is Reactive Programming?
By Luca Mezzalira
Everyday when we open our favourite editor or IDE taking a decision, often we use our favourite programming language, sometimes we study a new one but, consciously or unconsciously, we are taking the decision of what kind of programming paradigm we are going to work with.
I don’t want to start immediately with many technical terms because we will have enough time to learn them reading this book, but it’s important that you understand what is the benefit of working in a “reactive way”.
If you read on blog posts or articles in the web, few of them are going to explain reactive programming with the spreadsheet cells example, where spreadsheet cells are reacting to changes happening in other cells after user input. This is definitely a good example but in my opinion we can do better than this.
I’m sure you are familiar with the dependency injection pattern where an object is injected via the constructor or in a public method exposed by a class or module. This pattern leverages several benefits like decoupling between 2 objects, the possibility to test the hosting object in isolation without creating dependencies and so on.
Usually when we use dependency injection we are use to define an interface as argument in the hosting object and then we can interact with the methods available in the injected object.
The injected object in this case is used as an interactive object, because the host knows exactly what is the contract and how to use it.
In reactive programming instead, the hosting object will just subscribe to the injected one and it will react to the propagation of changes during the application lifetime.
Figure 1. Interactive vs Reactive programming: in Reactive Programming the producer is A and the consumer is B
We can immediately grasp the main difference between the two approaches:
- in the first example if we have to understand who have affected the state of the ingested object, we will search across all the projects that are interacting with
- in the reactive one, we are certain that any manipulation would occur inside the injected object therefore we will have a stronger separation of concerns between objects.
Because the hosting object is reacting to any value propagated inside the object injected, our program will be up-to-date without the need of implementing any additional logic.
About the Author
In his spare time, Luca writes for national and international technical magazines and acts as a technical reviewer for several publishers. He has spoken at a wide range of conferences.
This blog post is excerpted from the book Front-End Reactive Architectures by Luca Mezzalira.