Observables in RxJS

Welcome back, web developers, In today’s AppDividend Tutorial, I have briefly described Observables in RxJS. Observables are pioneer concept in Reactive Programming. If you do not know what is Reactive Programming, then check out my article on this website  What is Reactive Programming in Javascript.

We will see following topics in this article.

  1. What is an observable?
  2. Difference between Observable and Promise
  3. Difference between Array and Observable
  4. Creating an observable
  5. Unsubscribe from an observable

What is Observables

Observables are simply a data streams or collections which arrive at a time. Observables are objects that can notify subscribers when the change is happening. We can wrap Observables as an object which contains following things.

  1. Data Streams
  2. Some methods (next(), error(), complete())
Observables in RxJS
Observables in RxJS

Promises vs. Observables

If you do not know what promise is, check out my another article on this website called Promises in ES6Promises are a way of saying that till now I have not any data while in a pending state, but in future, It will surely either resolve or reject the data depending on the result. However, Promises are different from Observables. Let us take an example.

Example #1 (Promise)

//main.js

let prom = new Promise((resolve, reject) => {
   setTimeout(()=>{
      resolve('hello');
   },1000);
   console.log('Invoked Promise')
});

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Output

Invoked Promise

That means, till now in above code, we have not invoked promise. Still, It will run and give us a logged statement. Now check the same for Observables.

Example #1 (Observable)

//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
    },2000)
    console.log('Invoked Observables');
})

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  2.  RxJS library not found in this code snippet.
  3. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1. What is Reactive Programming in Javascript?  Follow this article strictly and put above code in the main.js file.

Output

// nothing will show up here

That means, Observables are lazy, We want to subscribe it to get the output from it, whereas Promises are not lazy.

//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
    },2000)
    console.log('Invoked Observables');
});
obs.subscribe();

Output

Invoked Observables

Arrays vs. Observables

Arrays vs.Observables
Arrays vs.Observables

Array elements do not relate to anytime. It just arrives, forms a Data Structure and we can apply some Higher Order Functions on it, and then we can get a new array.

Observables are entirely different from Arrays, as they arrive in various time, so all the elements behave like a data streams. So we can sum it up as Observables are data streams comes at a time. It return an object on which we can call next(), error() and complete() method on it.

Creating an Observable

// main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
    },2000);
});
obs.subscribe(data => console.log(data));

Output

hello

We have imported an observable library, and then we have created a new instance of an observable via invoking new keyword. We have passed the observer object to the constructor as a parameter. We have thrown a stream called ‘hello‘ via next() method on the observable so that when we subscribe to the observable, we get the data.

// main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello')
        observer.complete();
    },2000);
});
obs.subscribe(data => console.log(data),
            (error) => console.log(error),
            () => console.log('Done')
);

Output

hello
Done

If we call complete() method on an observable then, after all the collections have been done, it will fire done a callback, which accepts no argument but can assure that the stream of data is complete via subscribing the observer. So basically, subscribe() method has three callbacks

  1. We get original data via subscribing an observer.
  2. Error callback, if any error has been thrown from an observer.
  3. Complete callback invoked immediately if complete the data stream is completed.
//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        throw 'an error';
    },2000);
});
obs.subscribe(data => console.log(data),
            (error) => console.log(error),
            () => console.log('Done')
);

Output

Uncaught an error

Unsubscribe from an observable

//main.js

import {Observable} from 'rxjs-es';
let obs = new Observable(observer => {
    setTimeout(() => {
        observer.next('hello');
    },2000);
    return () => {
        console.log('Disposal called');
    }
});
let object = obs.subscribe(data => console.log(data),
            (error) => console.log(error),
            () => console.log('Done')
);
object.unsubscribe();

Output

Disposal called

We have unsubscribed the subscriber, and we no longer get the data. Instead, we got the confirmation that we have unsubsribed the data.

Memorable Points

  1. We want to make use of observables to handle, manage and compose asynchronous events.
  2. There are mainly three asynchronous events in a web browser 1) DOM Events 2) AJAX Requests 3) Animations. It can be used to model events, asynchronous requests, and animations.
  3. Observables represent push based async data source.
  4. It emits no data until consumer wants it.
  5. It can also be transformed, combined, and consumed using the Array methods like map(), filter(), reduce() and other higher order functions
If you still have doubt in this Observables in RxJS then ask in the comment below, I am happy to help you out.

You might also like More from author

Leave A Reply

Your email address will not be published.