Chapter 1. What is Reactive Programming?
Reactive Programming is both an overloaded term and a broad topic. As such, this book will focus on a specific formulation of Reactive Programming called Compositional Event Systems (CES).
Before covering some history and background behind Reactive Programming and CES, I would like to open with a working and hopefully compelling example: an animation in which we draw a sine wave onto a web page.
The sine wave is simply the graph representation of the sine function. It is a smooth, repetitive oscillation, and at the end of our animation it will look like the following screenshot:
This example will highlight how CES:
- Urges us to think about what we would like to do as opposed to how
- Encourages small, specific abstractions that can be composed together
- Produces terse and maintainable code that is easy to change
The core of this program boils down to four lines of ClojureScript:
(-> sine-wave (.take 600) (.subscribe (fn [{:keys [x y]}] (fill-rect x y "orange"))))
Simply by looking at this code it is impossible to determine precisely what it does. However, do take the time to read and imagine what it could do.
First, we have a variable called sine-wave
, which represents the 2D coordinates we will draw onto the web page. The next line gives us the intuition that sine-wave
is some sort of collection-like abstraction: we use .take
to retrieve 600 coordinates from it.
Finally, we .subscribe
to this "collection" by passing it a callback. This callback will be called for each item in the sine-wave, finally drawing at the given x and y coordinates using the fill-rect
function.
This is quite a bit to take in for now as we haven't seen any other code yet—but that was the point of this little exercise: even though we know nothing about the specifics of this example, we are able to develop an intuition of how it might work.
Let's see what else is necessary to make this snippet animate a sine wave on our screen.