Let’s Observe ReactiveX Observables

Reading Time: 5 minutes

Hello! there folks. Today I am going to try to make you understand one of the most interesting and important topics inside Angular domain – The Observables.

Angular 2 introduced us with observables. It uses Observables to handle async tasks, event handling and to handle multiple values. Observables are not part of angular itself neither of JS but are imported from ReactiveX library which offers solutions related to reactive programming for multiple languages and platforms. Angular uses RxJS which is the reactive extension library for JavaScript. However, Observables are being proposed to be added to the JS in its forthcoming iterations.

Image result for reactive x

ReactiveX or Reactive Extensions is a set of open source libraries for composing synchronous and asynchronous tasks effectively and efficiently, which is based on observer pattern.

First things first! What are Observables?

Observables are lazy snail-like creatures that eat multiple values or energy sources over a period of time. It opens a channel for communication where multiple values are emitted over time. Pretty easy right?

Image result for observable

Think it as of newsletter we only deliver the newsletter to those who have a valid subscription for it or think of it as Internet Service offered by mobile devices, it is only available to people who subscribed to it.

In angular docs, you may find this –

You can think of an observable as an array whose items arrive asynchronously over time. Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its http client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). Observables are a proposed feature for ES 2016, the next version of JavaScript.

So, why we use Observables?

There is two explanation for this, one is a simple one and other is a complicated one. Which one do you prefer? Worry not, I will provide both –

Image result for angular observables

For complicated jargon, you can visit – here

For simple living beings –

  • Easly composable – they do not jitter when nesting like futures with complexity overhead.
  • Butterly flexible – not only support the emission of single values but also the sequence of values or even infinite streams. For example, You are a subscriber and you have subscribed to newsgroup agency which delivers a newsletter every day till the day you have paid but you can also subscribe to another newsletter from the same agency, there is no constraint that you can only consume from only one publisher. Got it?
  • Have a do not care attitude towards the implementation. Observables can be implemented in any of the following ways: –
    • Thread pool
    • Event loop
    • Non – blocking IO
    • Actors
  • Use in HTTP requests – Observables make it easy to get and post data via Http in an async fashion. Like its a child’s play.

That’s why we prefer Observables and angular heavily implements it for asynchronously populating the UI from an external data source, router and forms module use it to listen to user input, event emitter class extends observables, HTTP get and post request uses observables and god knows where else it is used.

Now let’s have some hands on it –

For that, we will try to create an observable on our own –

It will be good for you if you know how to create observable on your own, don’t worry its really easy. It involves four steps –

Step 1: Creating observables
Creating observables is easy, just call the new Observable() and pass along one argument which represents the observer. Therefore I usually call it “observer” as well.

Step 2: Subscribing to observables
Remember, observables are lazy. If you don’t subscribe nothing is going to happen. It’s good to know that when you subscribe to an observer, each call of subscribe()will trigger it’s own independent execution for that given observer. Subscribe calls are not shared among multiple subscribers to the same observable.

Step 3: Executing observables
The code inside an observable represents the execution of the observables. On the parameter that was given when creating the observable there are three functions available to send data to the subscribers of the observable:

Image result for observable
  • “next”: sends any value such as Numbers, Arrays or objects to it’s subscribers.
  • “error”: sends a Javascript error or exception
  • “complete”: does not send any value.

Calls of the next are the most common as they actually deliver the data to its subscribers. During observable execution, there can be an infinite call to the observer.next(), however, when observer.error() or observer.complete()is called, the execution stops and no more data will be delivered to the subscribers. Here’s the dirty example –

import { Observable } from "rxjs/Observable"

// create observable
const simpleObservable = new Observable((observer) => {
    // observable execution
    observer.next("This is some text")

// subscribe to the observable

// dispose the observable

As you can see in the above example observables are created by using the new Observable() call, then subscribed to by an observer, executed by calling the next() and disposed by calling unsubscribe().

Step 4: Disposing observables
Because observable execution can run for an infinite amount of time, we need a way to stop it from executing. Since each execution is run for every subscriber it’s important to not keep subscriptions open for subscribers that don’t need data anymore, as that would mean a waste of memory and computing power.

When you subscribe to an observable, you get back a subscription, which represents the ongoing execution. Just call unsubscribe()to cancel the execution.

The Conclusion

I believe it would be nearly impossible to manage async functions and other functionalities which depends on async tasks, without the help of RxJS library.

This was just the glimpse of the Rxjs library and observables. I hope you have some clearness on the word observables in the angular domain and you will try to implement it in your future projects, till then stay tuned for more interesting blogs 
Also, we have added some links for you to follow –



Written by 

Shubhrank Rastogi is a FrontEnd Software Consultant at Knoldus Software LLP. He has done MCA from BVICAM, Paschim Vihar, New Delhi. He has a decent knowledge of Web Technologies like JS, TS, Angular, and currently exploring the Ionic framework and React library. He is also a die-hard fan of futuristic gadgets and a tech-savvy person who has a good appetite for delicious food.