Updated April 18, 2023
Introduction to Observable JavaScript
Observable JavaScript represents a progressive way of handling events, async the activity, and multiple values in JavaScript. These observables are just the functions that throw values and Objects known as observers subscribe to such values that define the callback functions such as error(), next() and complete(). These objects are passed as arguments to observable functions and these observable functions call observer methods based on the HTTP requests, events, etc. This allows the observer to “listen” for state change emitted by observable function. Here, we shall see in depth and how it is implemented with few examples.
Syntax:
Observable JavaScript does not have any particular syntax, it is a class that is defined in JavaScript’s RxJS library, and imported as below,
import { Observable } from 'rxjs';
Observables in JavaScript are like callbacks and promises, which are responsible for handling asynchronous requests. RxJS library has introduced Observables. Hence, before understanding what Observable is, we need to know 2 communication models i.e., push and pull.
Both protocols are concepts of how data producers communicate with data consumers.
Push Model: Here, producers determine when to send the data to the customer and the customer has no idea when will the data be received.
Pull Model: Here, consumers determine when data will be received from the producer, and the producer does not know when data will get delivered.
Observables create pub subsystems based on an observable design pattern that makes observable design patterns popular with asynchronous programming in all modern JavaScript frameworks such as React and Angular libraries.
Observables are not inherited in JavaScript, unlike Promises, hence, React and Angular rely on RxJS library for implementing such observables. RxJS is known as Reactive Extension for JavaScript and this library defines Observable class along with other supporting methods for Reactive programming.
Examples
Let us discuss examples of Observable JavaScript.
Example #1: Invoking Observable in JavaScript
import { Observable } from 'rxjs';
let observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hi This will invoke Observables')
},5000)
console.log('Observables invoked!');
});
observable.subscribe();
Output:
Here, as observables are part of RxJS, the above programming shows Invoking of Observables with a timeout of 5 milliseconds.
Example #2: Observable JavaScript for Wrapping Array to Observable
import { Observable } from 'rxjs';
const ArrayToObservableWrap = array => {
return new Observable(subscriber => {
for (let i of array) {
subscriber.next(i);
}
});
};
const arrVal = [6, 7, 5, 4, 3, 2, 9];
const observable = ArrayToObservableWrap(arrVal);
observable.subscribe(value => console.log('Subscriber1: ' + value));
observable.subscribe(value => console.log('Subscriber2: ' + value));
Output:
As per the above output, function() ArrayToObservableWrap takes the array as a parameter and wraps the array to an observable.
Example #3: Invoking Observables and print value using Subscribe
import { Observable } from 'rxjs';
const obs = new Observable(subscriber => {
subscriber.next(34);
subscriber.next(22);
subscriber.next(67);
subscriber.next(89);
subscriber.next(12);
setTimeout(() => {
subscriber.next(6);
subscriber.complete();
}, 2000);
});
console.log('Before Subscribe!');
obs.subscribe({
next(i) { console.log('subscribed value: ' + i); },
error(error) { console.error('There is something error in the code: ' + error); },
complete() { console.log('values subscribed'); }
});
console.log('After Subscribe!');
Output:
Observables are just like functions with no arguments but will generalize to have multiple values. We will see How Observables act as functions with an example,
Example #4: Observables as functions in JavaScript
import { Observable } from 'rxjs';
const obs = new Observable(subscriber => {
console.log('Observable can act as functions in JavaScript using RxJS');
subscriber.next(32);
});
obs.subscribe(i => {
console.log(i);
});
obs.subscribe(j => {
console.log(j);
});
Output:
So here Observable is being used similar to a function in JavaScript.
Observables deliver values either in a Synchronous or Asynchronous manner. The main difference between Observable and a function is JavaScript is that Observables can return multiple values, unlike functions.
Disposing Observable Executions in JavaScript
As Observable executions are infinite and are common for Observer to abort any execution in a finite time, for which an API is needed for canceling execution.
Each execution is exclusive to a single Observer and once the observer is done with receiving values, there has to be a way to stop execution to avoid wastage of computation power or the memory resources.
The main reason behind the usage of Observables is to get safer and composable with Operators.
Conclusion
With this, we shall conclude the topic “observable JavaScript”. We have seen what is Observable JavaScript and what does it mean. We have also seen how it has been a part of the RxJS library and how it can be imported into JavaScript programs. We have seen the implementation of such Observables with few examples and have also discussed Disposing of Observables to save memory in JavaScript. Thanks! Happy Learning!!
Recommended Articles
This is a guide to Observable JavaScript. Here we discuss Introduction, syntax, examples with code implementation respectively. You may also have a look at the following articles to learn more –