Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is observable in JavaScript

A Glance into Observables

In the world of JavaScript, there's a concept known as Observables. Now, if you're new to programming, you might wonder, "What on earth is an Observable?" Let's unpack this interesting concept together, and by the end of this blog, you'll not only understand what an Observable is but also how to use it in your JavaScript projects.

A Simple Analogy

To ease into the topic, let's use a simple analogy. Imagine you're waiting for your favorite band to release their new album. You can choose to check their website every day to see if the album is out. That's one way, but it's not the most efficient. A better way would be to subscribe to their newsletter, and they will notify you when the album is released. In this scenario, the band's newsletter is like an Observable, and you, waiting for the updates, are the observer.

Understanding Observables

In JavaScript, an Observable is essentially a function that can produce a stream of values to an observer over time. This makes it easy to handle asynchronous or even synchronous events. Observables are part of the Reactive Extensions (RxJS) library, which provides a collection of powerful tools for handling asynchronous data streams.

Now, what's an asynchronous data stream you ask? Well, imagine you're trying to catch fish in a river. The fish are like data points, and the river is like an asynchronous data stream. The fish don't all come at once; they come at different times, just like data in an asynchronous stream.

Let’s Dive into Code

First, we need to install the RxJS library. We can do this using npm (Node Package Manager), a tool that helps us install JavaScript libraries.

npm install rxjs

After installing RxJS, we can create an Observable. Let's walk through a simple example.

const { Observable } = require('rxjs');

const observable = new Observable(subscriber => {
  subscriber.next('Hello');
  subscriber.next('World');
});

observable.subscribe(value => console.log(value));

In this example, we create an Observable that emits 'Hello' and 'World'. The next method is used to deliver some value to the observer. To start receiving these values, we need to subscribe to the Observable, as we do in the last line.

When you run this code, you'll see 'Hello' and 'World' printed, which shows us that the Observable has successfully delivered these values to the observer.

Observables in Action

Observables are not limited to just emitting strings like 'Hello' and 'World'. They can emit any JavaScript object. Let’s look at another example where an Observable emits multiple values over time.

const { Observable } = require('rxjs');

const observable = new Observable(subscriber => {
  let count = 0;
  const id = setInterval(() => {
    subscriber.next(count++);
    if (count > 5) {
      subscriber.complete();
    }
  }, 1000);

  return () => {
    console.log('Called just before unsubscribe.');
    clearInterval(id);
  };
});

const subscription = observable.subscribe({
  next(value) { console.log(value); },
  complete() { console.log('Completed sequence.'); },
  error(err) { console.log('Error occurred: ', err); },
});

setTimeout(() => subscription.unsubscribe(), 7000);

In this example, our Observable emits an increasing number every second. After it emits five values, it completes the sequence. If any error occurs during this process, it would be handled in the error() function. We also demonstrate how to unsubscribe from an Observable after a certain period.

Wrapping Up

Observables are like magical boxes that produce values over time. They can be anything from strings, numbers to complex JavaScript objects. They are a powerful way to handle data streams in JavaScript, especially when dealing with asynchronous events.

Remember our band album analogy? Just like subscribing to the band's newsletter saved you a lot of effort, using Observables can save you from constantly checking for data updates. Instead, data will come to you when it's available.

So keep learning, keep exploring, and soon you'll be harnessing the power of Observables in your JavaScript adventures. Who knows, maybe you'll become the rockstar of JavaScript programming, producing hit "albums" of your own!