What is Observables in JavaScript

Observables in JavaScript are a way of handling events, async activity, and multiple values. They are functions that throw values, and objects called observers subscribe to these values. In addition, observers define callback functions for next(), error(), and complete().

Observables create a pub-sub system based on the observable design pattern. This makes observables popular with async programming in modern JavaScript frameworks like Angular and libraries like React.

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

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

Syntax

import { Observable } from 'rxjs';

How to create an Observable in JavaScript

You can use the Observable constructor from the RxJS library. The constructor takes a function as its argument called a subscriber function. The subscriber function receives an observer object as a parameter, which has methods for emitting values, errors, and completion signals.

import {Observable} from 'rxjs-es';

let obs = new Observable(observer => {
  setTimeout(() => {
    observer.next('hello')
   },2000);
});

obs.subscribe(data => console.log(data));

Output

hello

We imported an observable library and then created a new instance of an observable by invoking a new keyword.

We passed the observer object to the constructor as a parameter. Finally, we have thrown a stream called ‘hello’ via the next() method on the observable to get the data when we subscribe to the observable.

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

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

  1. We get original data by subscribing to 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.
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

How to unsubscribe from an observable in JavaScript

To unsubscribe from an observable in JavaScript, you must have a Subscription object. This is the object returned from every Observable.subscribe() call. You can call the unsubscribe() method on the Subscription object to cancel Observable executions and release resources.

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 unsubscribed the subscriber, and we no longer get the data. Instead, we got the confirmation that we had unsubscribed the data.

That’s it for the JavaScript Observables.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.