Let’s see what being reactive means in programming by considering a simple example.
let a1 = 2; let b1 = 4; let c1 = a1 + b1; // c1 = 6
This code adds the values of the variables a1 and b1, and c1 is equal 6. Now let’s add a couple of lines to this code modifying the values of a1 and b1:
let a1 = 2; let b1 = 4; let c1 = a1 + b1; // c1 = 6 a1 = 55; // c1 = 6 but should be 59 b1 = 20; // c1 = 6 but should be 75
While the values of a1 and b1 changed, c1 didn’t react to these changes and its value is still 6. Of course, you can write a function that adds a1 and b1 and invokes it to get the latest value of c1, but this would be an imperative style of coding where you dictate when to invoke a function to calculate the sum.
Wouldn’t it be nice if c1 would be automatically recalulated on any a1 or b1 changes? Think of any spreadsheet program like Microsoft Excel, where you could put a formula =sum(a1, b1) into the c1 cell, and c1 would react immediately on the changes in a1 and b1. In other words, you don’t need to click on any button to refresh the value of c1 – the data are pushed to this sell.
In the reactive style of coding (as opposed to imperative one), the changes in data drive the invocation of your code. Reactive programming is about creating responsive event-driven applications, where an observable event stream is pushed to subscribers, which observe and handle the events.
In software engineering, Observer/Observable is a well-known pattern, and it’s a good fit in any asynchronous processing scenario. But reactive programming is a lot more than just an implementation of the Observer/Observable pattern. The observable streams can be canceled, they can notify about the end of a stream, and the data pushed to the subscriber can be transformed on the way from the data producer to the subscriber by applying one or more composable operators (you’ll see some of them in Part 2 of this series).
Getting familiar with RxJS terminology
We want to observe data, which means that there is some data producer that can be a server sending data using HTTP or WebSockets, a UI input field where the user enters some data, an accelerometer in a smart phone, et al. An observable is a function (or an object) on the client that gets the producer’s data and pushes them to the subscriber(s). UI An observer is an object (or a function) that knows how to handle the data elements pushed by the observable.
Hot and cold observables
There are two types of observables: hot and cold. The main difference is that a cold observable creates a data producer for each subscriber, while a hot observable creates a data producer first, and each subscriber gets the data from one producer starting from the moment of subscription.
Let’s compare watching a movie on Netflix vs going into a movie theater. Think of yourself as an observer. Anyone who decided to watch “Mission Impossible” on Netflix will get the entire movie regardless of when he or she hit the button play. Netflix creates a new producer to stream a movie just for you. This is a cold observable.
If you go to a movie theater and the showtime is 4PM, “the producer is created” at 4PM and the streaming begins. If some people (subscribers) were late to the show, they missed the beginning of the movie and will watch it starting from the moment of arrival. This is hot observable.
A cold observable starts producing data when some code invokes a subscribe() function on it. For example, your app may declare an observable providing a URL on the server to get certain products. The actual request will be made only when you subscribe to it. If another script will make the same request to the server, it’ll get the same set of data.
A hot observable produces data even if there are no subscribers interested in the data. For example, an accelerometer of your smartphone produces multiple data about the position of your device even if there no app that subscribes to this data. Or a server can produce the latest stock prices even if no user is interested in this stock.
The main players of RxJS
The main players of RxJS are:
* Observable – data stream that pushes data over time
* Observer – consumer of an observable stream
* Subscriber – connects observer with observable
* Operator – a function for the en-route data transformation
I’ll introduce each of these players in this series by showing examples of their use. For a complete coverage, refer to RxJS documentation.
Observable, observer, and subscriber
As stated earlier, an observable gets data from some data source (a socket, an array, UI events) one element at a time. To be precise, an observable knows how to do three things:
* Emit the next element to the observer
* Throw an error on the observer
* Inform the observer that the stream is over
Accordingly, an observer object provides up to three callbacks:
* The function to handle the next element emitted by the observable
* The function to handle errors thrown by the observable
* The function to handle the end of stream
The subscriber connects an observable and observer by invoking the method subscribe() and disconnects them by invoking unsubscribe(). A script that subscribes to an observable has to provide the observer object that knows what to do with the produced elements. Let’s say we created an observable represented by the variable someObservable and the observer represented by the variable myObserver. Then you can subscribe to such an observable as follows:
let mySubscription: Subscription = someObservable.subscribe(myObserver);
To cancel the subscription, invoke the unsubscribe() method:
How an observable can communicate with the provided observer? It does it by invoking the following functions on the observer object:
* next() to push the next data element to the observer
* error() to push the error message to the observer
* complete() to send a signal to the observer about end of stream
You’ll see an example of using these functions in the next article of this series.
RxJS offers multiple ways of creating an observable depending on the type of the data producer. As an example, the data producer a DOM event, a data collection, a custom function, a WebSocket and more. Below are some examples of the API to create and observable:
* Observable.of(1,2,3) – turns the sequence of numbers into an Observable
* Observable.create(myObserver) – returns an Observable that can invoke methods on myObserver that you will create and supply as an argument
* Observable.from(myArray) – converts an array represented by the variable myArray into an Observable. You can also use any an iterable data collection or a generator function as an argument of from().
* Observable.fromEvent(myInput, ‘keyup’) – converts the keyup event from some HTML element represented by myInput into an Observable
* Observable.interval(1000) – emits a sequential integer (0,1,2,3…) every second
Let’s create an observable that will emit 1,2, and 3 and subscribe to this observable:
Rx.Observable.of(1,2,3) .subscribe( value => console.log(value), err => console.error(err), () => console.log("Streaming is over") );
Note that we pass three fat arrow functions to subscribe(). These three functions are the implementation of our observer. The first function will be invoked for each element emitted by the observable. The second function will be invoked in case of an error providing the object representing the error. The third function takes no arguments and will be invoked when the observable stream is over. Running this code sample will produce the following output on the console:
1 2 3 Streaming is over
To see it in action in CodePen, follow this link. Open the console view at the bottom to see the output.
The basic terms are covered. In the next article of this series, I’ll introduce you to some RxJS operators that are used to transform the emitted items while they’re moving from observable to the observer.
11 thoughts on “RxJS Essentials. Part 1: Basic terms”
“Let’s say we created an observer represented by the variable someObservable and the observer represented by the variable myObserver.”
Did you want to say, “Let’s say we created an observable represented by the variable someObservable and the observer represented by the variable myObserver.”
That’s correct, thanks.
Looks like your video has been removed from safaribooksonline.com. could you please check?