Reactive Programming and the Observer Pattern

May 7, 2018 Oclemy Reactive Programming 2 minutes, 9 seconds

Reactive Programming has become popular in recent years. Mostly Reactive Programming get implemented using Functional Programing Languages.

Reactive Programming involves two main concepts:

  1. Code that reacts to events.
  2. Code handles values in realtime as they change, propagating those changes to every part of the code that had subscribed to be notified.

However, Reactive Programming can be done imperatively. And in fact approaching Reactive Programming imperatively is what leads to what we normally call callbacks.

Ultimately, whether it is Reactive Programming or not, there is no magic. Because at the hardware and Operating System level everything is imperative. Computers have to be told explicitly what we do.

Thus reactive programming is just an abstraction. Imperative Programming, at a high level like Object Oriented Programming, is an abstraction too.

However, Reactive Programming is of a higher level of abstraction than high level imperative programming. In fact it is an abstraction over imperative programming, so as to allow us build programs of asychronous and event-driven nature in an simpler manner. It's simpler since saves from having to care of complex imperative interactions of states across threads and networks.

Reactive Programming is ultimately aimed at solving concurrency and parallelism issues in a more declarative manner. Trying to do this in an imperative way is whate has led to the infamous callback hell. Callbacks are great if you have only a single event stream. However, if you have multiple events or asynchronous responses which you need to combine, this can lead to the callback hell.

Reactive Programming involves operations on Streams of Data.

These streams are any sequences of events that happen e.g user inputs, responses from web services, collections of data, even a single variable.

These streams originate from somewhere. That somewhere we call the Source. So the source emits the sequence of data.

But there is also some parties within your code that is interested in those streams of data. They observe the stream or flow and react to each emitted item.

Some of the areas wheer Reactive Programming is commonly applied include:

  1. Latency-bound IO events ffrom disk or network.
  2. Processing User events like mouse clicks, keyboayd typing, device sensor signals etc.
  3. Processing data from producers you have little or no control over like server,hardwares etc.

The Observer Pattern

At the core of Reactive Programming is a design pattern called called Observer Pattern.

There are two entities in the Obersver Pattern:

  1. Observer - An entity that observes the changes of one or more subjects.
  2. Subject - An entity that keeps a list of its observers and automatically informs them when its state changes.