Logo for the raulrpearson.com site

Reactive programming

This week I've spent some time fascinated with this concept of reactive programming. It started because I found parts of the Svelte website referencing the idea as well as the video I shared last week.

Put simply---and abstractly---reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change. So what. Who cares. How do we use that idea when writing our programs?

The introduction I spent most time with is The introduction to Reactive Programming you've been missing by Andre Staltz. It's quite concise, considering the amount of ground it covers. It also provides a non-trivial example to present some of the concepts and methods. He uses JavaScript and RxJS, which seems to be the most popular choice when wanting to use reactive programming in JavaScript.

In order to understand and reason about reactive systems, someone came up with marble diagrams. Andre presents the following diagram, representing a possible implementation of a multiple click detector using reactive programming abstractions:

A marble diagram

Each of the horizontal lines represents a stream of events. These streams are also called observables because having parts of the program subscribe to---i.e. observe---other parts of the program is an important pattern in reactive programming.

A program would consist of a set of transformations to observables. In the above example, a buffer is applied to the click stream. This transformation creates a new stream that clumps up clicks that happen within 250ms of each other. A map transformation is applied to this clumped up stream of clicks to produce yet another stream, of click counts in this case. Finally, a filter transformation is applied to generate our target stream of multiple clicks.

It seems a bit obtuse at first, but after a while you start to see that it provides a rather elegant and concise way of codifying certain type of program logic.

I don't think I'll keep looking into reactive programming at the moment---I feel like I still have to master more prosaic ideas and skills---but it'll be on my radar. I am going to keep looking into Svelte, and that seems like it will enable me to start integrating the reactive programming mindset.