Reactive Programming in the UI: RxJS from Grounds up — Part 1
By: Dr. Gabriel Schenker
Tags: Rxjs, Introduction, Reactive Programming

TLTR;

In this post we learn the core concepts of reactive programming such as Streams, Producers, Consumers, Observables and Observers, and implement a first hello world type of application with RxJS.

Introduction

Event driven architecture (EDA) is an architecture style where components of an application interact with each other via events rather than via request-response type of interactions. This makes it easier to keep the individual components autonomous and loosely coupled. EDA has been used in the backend of enterprise and other applications quite for some time and is well established.

More and more this style of programming has also been embraced by frontend developers. Modern SPA frameworks such as React or Angular have built-in functionality or use libraries to enable this style of programming.

In this post and a series of follow-up posts I want to introduce the principles of reactive programming from grounds up, using the minimum possible setup (basically HTML5 and plain vanilla JS plus some simple CSS). I want to show various concepts using simple to follow and hopefully interesting use cases. I have chosen the library RxJS for my samples as it is very popular and natively included in newer versions of Angular.

As stated above, I want to introduce the concepts of reactive programming without having to first install a lot of software, libraries or event frameworks. Initially I explicitly do not use a SPA such as React or Angular to demonstrate the concepts since I want to avoid unnecessary complexity. The reader should be able to follow the samples and not be distracted by elements that do not have anything to do with what I want to show. So, let’s get started…

Plan of Attack

My goal is to cover the following topics in the first two posts of the series:

Part 1 (this post):

Introduction into Streams, Producers and Consumers

Introduce Observables and Observers

Setting up the environment

Creating a hello world type application using RxJS

Part 2:

Use operators to manipulate a stream of values

Implementing a countdown using RxJS

Simulating a stock ticker with RxJS

What is a Stream

When working with a reactive architectural style then you will often hear the terms stream or stream of data. Now what is a stream? We can illustrate a stream as follows:

Representation of a Stream

As you can see in the picture above, a stream is an (ordered) sequence of data packets. We can number those data packages as we have done in the picture. We have Item 0 , Item 1 to Item n shown. Since in our case the time axis progresses from left to right — indicated by the arrow — the older data packages are on the left side and have a lower sequence number. We have indicated the very first appearing data package with index zero (0).

On the image we also show the start of the stream, that is the moment the first data item was produced as well as the now. It is important to notice that a stream in many cases has no end. More data items may be produced in the future. Sometime a stream even produces an infinite number of items.

Now, a stream needs “somebody” to produce the data items and “somebody else” to consume those items to be of any value. We call the former a producer and the latter a consumer. An image is worth a thousand words, thus let me show what I mean:

A stream with producer and consumers

Normally, when dealing with streams one has a single producer per stream and one to many consumers. The consumers consume the data packages. Depending on the situation, consumers can actively poll the stream and ask if there are more items available or they can be notified by the stream that a new data item is available. The former is called a pull mechanism or pattern whilst the latter is called a push mechanism. When working in the UI with RxJS we will use the push mechanism, but if you e.g. use Apache Kafka in the backend, then you will be familiar with the pull mechanism.

What are Observable and Observer?

This is a post about reactive programming in the UI in general and the RxJS library in specific and thus we have to introduce the terminology that is used in that context. When dealing with RxJS one usually does not explicitly talk about streams, producers or consumers, but rather about Observables and Observers. Thus let’s put those two concepts in relation to what we have learned so far.

An observable is a kind of abstraction of a stream. The observable produces a potentially infinite stream of data items. On the other hand an observer is an object (or function) that consumes the data items produced by the observable. Thus we can say that an observer is the equivalent of a consumer and the observable is the equivalent of a stream. I know, I know, this is overly simplified but bare with me…

Similar to a stream that can have many consumers an observable can have many observers that consume the data items it produces.

Sample Marbles Diagram

An observable is often pictured in a so called Marbles Diagram as shown above. The individual data items are the marbles that are indexed with an increasing number. Also shown in the above diagram is a line denoted with end. This indicates that the observable produces a finite number of items and then ends. In our case it is 4 items. But that is only a special case. An observable can produce zero to an infinite number of data items.

To consume the data items produced by the observable an observer has to subscribe with the observable. Only then will the observable push (newly) produced items to the observer.

Observer subscribing to an Observable

In the above image I have shown how first an observer needs to subscribe to the observable such as that in a second stage the observer can consume the data that the observable pushes at it. Finally, when the observer is done, it can unsubscribe from the observable and the observable will stop to push any further data.

Now that we have a good understanding of the base concepts, let’s start to do some coding. We start by setting up our development environment.

Preparing the Environment

In all my examples I am going to use Visual Studio Code as my source code editor. I highly recommend this editor to you as it is by far the most popular code editor and runs on any platform, be it MacOS, Linux or Windows. Visual Studio Code (or VS Code as it is often called) is light weight and supports Web development natively or through many powerful plugins that you can download for it.

Open a terminal and navigate to your home folder with:

cd ~

Then in your home folder create a parent folder called rxjs-fundamentals for all the samples we will create in this and subsequent posts:

mkdir rxjs-fundamentals && cd rsjs-fundamentals

From within this parent folder we just created open VS Code by typing

code .

We are now ready to implement our first sample with RxJS.

Hello World in RxJS

In VS Code create a new folder called hello-world . In this folder create two new files called index.html and main.js . To the main.js file add the following code snippet:

<!DOCTYPE html>

<head>

<meta charset="UTF-8">

<title>RxJS Hello World</title>

</head> <body>

<h1>RxJS Hello World</h1>

</body>

</html>

It is the most simple skeleton for a new HTML5 page. Now we want to use the RxJS library in our samples and thus we add a script tag to download this library from a CDN. We add the script tag in the <body> right after the <h1> tag. Your content should now look like this:

The index.html page with the import of the RxJS library

We will write our own JavaScript code in the file main.js we added earlier. To have that code available in our HTML page we add another script tag right after the first one which imports our main.js file:

<script src='./main.js'></script>

Finally we add a <div> to the page inside which we will display the results of our code that we are going to write in a bit. We give this <div> a class of container :

<div class="container">undefined</div>

Our final HTML page will now look like this:

We are now ready to do some coding. Open the main.js file and add the following statement to access the interval function from rxjs :

const { interval } = rxjs;

Note that the rxjs object is available to us since we imported the RxJS library via the script tag in the HTML page.

The interval function can be used to generate an (endless) stream of numbers starting from 1 every given interval. To e.g. generate a new number every second we use the function interval(1000) . Now, having a stream of numbers generated is useless until we can do something with it. For this we need to subscribe to the stream and define what shall happen with each number the stream is generating. Add this code to your file:

const container = document.querySelector('.container');

interval(1000)

.subscribe(x => container.innerHTML = x);

First we are searching the <div> with class container using the querySelector function of the DOM. Inside this container we will want to display the numbers that the interval creates. We then use the interval function and subscribe to it. Remember, the interval function is generating an endless stream of increasing numbers.

The subscribe function expects a function as parameter describing what to do with the generated values. In our case we use the lambda function x => container.innerHTML = x to declare that we want to display the number x inside the div . Your main.js file should now look like this:

Now we are ready to run this very first example. Open the page in your browser.

To make things easy I recommend that you install the extension “open in browser” for VS Code. Once installed you can open a terminal inside VS Code and just type start index.html if you’re working on Windows or open index.html if you’re on a Mac. Or even more quickly, if you’re in the HTML page you want to open just press Alt-B to open the page in the browser.

You should see something similar to this:

Hello world running in the browser

You will notice the number that is counting up endlessly, every second displaying the next value. This is rxjs in Action.

You can see the full example on CodePen.

Summary

In this first part of a series of upcoming posts I have introduced and illustrated the concept of streams, producers and consumers. I then have described the analogous concepts used in reactive programming in the UI, specifically when using the RxJS library. After the theory part I have given a quick rundown of my development environment before diving into the very first example where we implemented a hello world type of application using RxJS.

In my next post of this series I will introduce RxJS operators. Operators are pure functions and allow us to manipulate a steam of data in a side effect free way. Keep tuned.