Observables

Observables are potentially infinitely collections that return values one at a time asynchronously. i.e. there can potentially be some time passed between one value returned and the next.

 

Observable = Array + Infinity + Asynchronous
// OR
Observable = Promise + Returns many times
————— Value 1 ————— Value 2 ————— Value 3 ————— Value 4 —————|—>

In this the way, they are very similar to Promises. Promises can return one value after some time has passed. Observables returns potentially infinite values with some time passing between each of them.

 

Javascript




// Two states => resolve, reject
const promise = new Promise(resolve, reject);
  
promise
.then((data) => console.log("Data came back:" + data)) // Success
.catch((err) => console.error("No, Ew David", err)); // Error


 
 

Promises have two possible states: resolve, reject, Or in other words: complete, error.

 

Javascript




const observable = from([1, 2, 3, 4]);
  
// Three states => next, complete, error
observable.subscribe({
  next: (value) => console.log("Next value:", value),
  complete: () => console.log("Infinity is Done!!! ¯\_(ツ)_/¯ "),
  error: (err) => console.log("No, Ew Binod", err),
});


 
 

Observables add an extra state to the same concept: next, complete, error. One of the most popular Observable libraries in JavaScript is RxJS. What makes RxJS awesome is not just the concept of Observables but also the extensive array of Operators. These Operators can take action on Observables to allow complex asynchronous code to be easily composed in a declarative manner.

 

RxJs – Beginner’s Guide

Have you ever wondered how you can open a 10GB file on a device with only 4GB of RAM? Or how Netflix app can play a cloud-hosted 4K movie on your phone as soon as you press play? On a device, with 4GB of RAM, a 10GB file is effectively infinite. How does your device manage to load something that is infinite?

It has to load the file into memory in small chunks, read them, and discard them before loading more data into memory. It has to stream the data and process it in small chunks.

Similar Reads

What is a Stream?

The stream is a collection of data that is potentially infinite. It is a sequence of data coming in overtime. It can be thought of as items on a conveyor belt being processed one at a time....

Observables

...

RxJs Operators

Observables are potentially infinitely collections that return values one at a time asynchronously. i.e. there can potentially be some time passed between one value returned and the next....

Contact Us