Skip to main content

Understanding RxJS Observables and why you need them

rxjsobservables

What is RxJS?

RxJS is a framework for reactive programming that makes use of Observables, making it really easy to write asynchronous code. According to the official documentation, this project is a kind of reactive extension to JavaScript with better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. It is the official library used by Angular to handle reactivity, converting pull operations for call-backs into Observables.

Prerequisites

To be able to follow through in this article’s demonstration you should have:
// run the command in a terminal
ng version
Confirm that you are using version 7, and update to 7 if you are not.
  • Download this tutorial’s starter project here to follow through the demonstrations
  • Unzip the project and initialize the node modules in your terminal with this command
npm install
Other things that will be nice to have are:
  • Working knowledge of the Angular framework at a beginner level

Understanding Observables: pull vs push

To understand Observables, you have to first understand the pull and push context. In JavaScript, there are two systems of communication called push and pull.
pull system is basically a function. A function is usually first defined (a process called production) and then somewhere along the line called (this process is called consumption)to return the data or value in the function. For functions, the producer (which is the definition) does not have any idea of when the data is going to be consumed, so the function call literally pulls the return value or data from the producer.
push system, on the other hand, control rests on the producer, the consumer does not know exactly when the data will get passed to it. A common example is promises in JavaScript, promises (producers) push already resolved value to call-backs (consumers). Another example is RxJS Observables, Observables produces multiple values called a stream (unlike promises that return one value) and pushes them to observers which serve as consumers.

What is a Stream?

A stream is basically a sequence of data values over time, this can range from a simple increment of numbers printed in 6 seconds (0,1,2,3,4,5) or coordinates printed over time, and even the data value of inputs in a form or chat texts passed through web sockets or API responses. These all represent data values that will be collected over time, hence the name stream.

What are Observables?

Streams are important to understand because they are facilitated by RxJS Observables. An Observable is basically a function that can return a stream of values to an observer over time, this can either be synchronously or asynchronously. The data values returned can go from zero to an infinite range of values.

Observers and subscriptions

For Observables to work there needs to be observers and subscriptions. Observables are data source wrappers and then the observer executes some instructions when there is a new value or a change in data values. The Observable is connected to the observer who does the execution through subscription, with a subscribe method the observer connects to the observable to execute a code block.

Observable lifecycle

With some help from observers and subscriptions the Observable instance passes through these four stages throughout its lifetime:
  • Creation
  • Subscription
  • Execution
  • Destruction

Creating Observables

If you followed this post from the start, you must have opened the Angular starter project in VS Code. To create an Observable, you have to first import Observable from RxJS in the .ts file of the component you want to create it in. The creation syntax looks something like this:
import { Observable } from "rxjs";

var observable = Observable.create((observer:any) => {
    observer.next('Hello World!')
})
Open your app.component.ts file and copy the code block below into it:
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'ngcanvas';
  ngOnInit(): void {
    var observable = Observable.create()
  }
  
}

Subscribing to Observables

To tell RxJS to execute the code block on the Observable, or in a simpler term, to call the Observable to begin execution you have to use the subscribe method like this:
export class AppComponent implements OnInit{
  title = 'ngcanvas';
  ngOnInit(): void {
    var observable = Observable.create((observer:any) => {
      observer.next('Hello World!')
  })
  observable.subscribe(function logMessage(message:any) {
    console.log(message);
  })
}
This subscribe method will cause “hello world” to be logged in the console.

Executing Observables

The observer is in charge of executing instructions in the Observable, so each observer that subscribes can deliver three values to the Observable:
  1. Next value: With the next value, observer sends a value that can be a number, a string or an object. There can be more than one next notifications set on a particular Observable
  2. Error value: With the error value, the observer sends a JavaScript exception. If an error is found in the Observable, nothing else can be delivered to the Observable
  3. Complete value: With the complete value, the observer sends no value. This usually signals that the subscriptions for that particular Observable is complete. If the complete value is sent, nothing else can be delivered to the Observable.
This can be illustrated with the code block below:
export class AppComponent implements OnInit{
  title = 'ngcanvas';
  ngOnInit(): void {
    var observable = Observable.create((observer:any) => {
      observer.next('I am number 1')
      observer.next('I am number 2')
      observer.error('I am number 3')
      observer.complete('I am number 4')
      observer.next('I am number 5')
  })
  observable.subscribe(function logMessage(message:any) {
    console.log(message);
  })
}
}
If you run the application at this point in the dev server with
ng serve
When you open up the console in the developer tools your log will look like this:
error in console
You will notice that either the error value or complete value automatically stops execution and so the number 5 never shows up in the console. This is a simple synchronous exercise. To make it asynchronous, let us wrap timers around some of the values.
export class AppComponent implements OnInit{
  title = 'ngcanvas';
  ngOnInit(): void {
    var observable = Observable.create((observer:any) => {
      observer.next('I am number 1')
      observer.next('I am number 2')
      setInterval(() => {
        observer.next('Random Async log message')
    }, 2000)
    observer.next('I am number 3')
    observer.next('I am number 4')
      setInterval(() => {
        observer.error('This is the end')
    }, 6001)
    observer.next('I am number 5')
  })
  observable.subscribe(function logMessage(message:any) {
    console.log(message);
  })
}
}
This will appear like this in your browser console:
console errors
Notice that the display of value was done here asynchronously, with the help of the setInterval module.

Destroying an Observable

To destroy an Observable is to essentially remove it from the DOMby unsubscribing to it. Normally for asynchronous logic, RxJS takes care of unsubscribing and immediately after an error or a complete notification your observable gets unsubscribed. For the knowledge, you can manually trigger unsubscribe with something like this:
return function unsubscribe() {
    clearInterval(observable);
  };

Why Observables are so vital

  • Emitting multiple values asynchronously is very easily handled with Observables
  • Error handlers can also easily be done inside Observables rather than a construct like promises
  • Observables are considered lazy, so in case of no subscription there will be no emission of data values
  • Observables can be resolved multiple times as opposed to functions or even promises

Conclusion

We have been given a thorough introduction to Observables, observers and subscriptions in RxJS. We have also been shown the lifecycle process of Observables with practical illustrations. More RxJS posts can be found on the blog, happy hacking!

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...