Playing with Reactive Programming

I want you to consider the following program and think about the output logged in the console,

Is it 11 or 21? As most of you would guess correctly, the answer would be 11. That’s because, once the value of b is computed, it is no longer dependent on the value of a. As a result,  changing the value of a does not change the value of b.

Suppose the value of a changes over time, e.g., it may be a user input from a webpage that can be modified by the user anytime. And we want b to be calculated as soon as a is changed. A new programming paradigm called Reactive Programming is used for such problems.

An example of Reactive Programming would be a spreadsheet. If you have used it before, you know that when you write a formula for a cell like “=A1+B1″, the value of the cell gets modified as soon as the value in either cell A1 or cell B1 is modified.

Let us now modify our example using Reactive Programming. The value of a is going to change every 3 sec, and as soon as it does, b will be modified. The resulting reactive program is following:

The above example is implemented using RxJs, a popular reactive library for JavaScript. Let’s define few terms before we analyze the example. An Event Stream generates events over time. In our case, a is an event stream that generates a new random value every 3 sec. An event stream can be subscribed to, meaning whenever a new event happens all the subscribers will be notified. In this example, we have a subscriber for a, which means whenever a is changed, i.e., it has a new value, b is modified. If you want to test this example, you can download it from here (for the sake of brevity this example does not include proper error handling and cleanup).

Further Reading:

  1. Jafar Husain (from Netflix) explains Reactive Programming based on known design patterns and how it is being used in Netflix. [video]
  2. Why do we care about reactive systems – The Reactive Manifesto. [link]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: