Observables in JavaScript

Observables in JavaScript

A deep dive into the Reactive Javascript

·

8 min read

Introduction

In today's fast-paced world of web development, managing complex applications and making them responsive is essential. To achieve this, the developers turned to a powerful concept called "Observables". These observations are the secret sauce behind dynamic and reactive user interfaces, especially when combined with popular libraries like React.js.

Imagine your website as a bustling city with activity and information flowing like traffic. Observables act as a traffic controller, intelligently managing and managing this traffic. It allows your code to run asynchronously with asynchronous events by performing tasks such as updating the UI and managing application state.

In this article, we'll delve deeper into the world of observables, illuminate their main points, and learn how they can revolutionize the way you build web apps with React.js.

The Definition

An Observable object is a function that creates an observer and binds to an object. where the values are expected from a DOM element or an HTTP request, etc.

Here, an observer is an object with callback functions that get called when there is interaction with the Observable.

Some Background

Well! You must have read about asynchronous features in the JavaScript world. 'Asynchronous code' is that code runs in the background without blocking the execution of other code. It does not wait for any task to be finished.

Now, if you're thinking - what happens to the task that is not finished? The co-worker handles those unfinished tasks. Yes! In the background, a co-worker works and handles those unfinished tasks and once they are done, it sends data back.

This can bring up another question of how we handle the data that is returned. The answer is Promises, Observables, callbacks, and many more.

What are Observables?

An observable is a pattern that allows us to work with asynchronous data streams. It provides a way to represent and work with sequences of events or data over time. Observables can emit multiple values, either synchronously or asynchronously, and they can be subscribed to by observers who want to be notified whenever new values are emitted.

The observable pattern is closely related to the concept of a stream. A stream is an abstract representation of a sequence of data or events that can be observed. These streams can be thought of as data producers that emit values, and observers can subscribe to these streams to consume those values.

In JavaScript, observables are implemented as part of the RxJS library, which is a popular library for reactive programming. RxJS provides a wide range of operators that allow developers to manipulate and transform data streams in various ways.

Key Concepts of Observables

  • Observable: An observable represents a stream of data or events. It can be created using various methods provided by popular libraries like RxJS or can be implemented manually using JavaScript native APIs.

  • Observer: An observer is an object with methods that get called when there are new data or events in the observable stream. It provides hooks to react to these events and process the received data.

  • Subscription: A subscription connects an observer to an observable. It allows the observer to start receiving data and events from the observable. A subscription can be closed when you no longer want to receive updates, freeing up resources.

  • Operators: Operators are functions that allow you to manipulate the data or events emitted by an observable stream. They provide a way to filter, transform, or combine the data to suit your requirements. Operators can be applied to an observable using method chaining.

Observable Phases

There are four stages through which observables pass. They are:

  1. Creation

  2. Subscription.

  3. Execution

  4. Destruction.

Promises vs observables

As we know, promises are for handling async requests and observables can also do the same. But where do they differ?

  • Observables are lazy whereas promises are not

    This is pretty self-explanatory: Observables are lazy, that is we have to subscribe to observables to get the results. In the case of promises, they execute immediately.

  • Observables handle multiple values unlike promises

    Promises can only provide a single value whereas observables can give you multiple values.

  • Observables are cancelable

    You can cancel observables by unsubscribing it using the unsubscribe method whereas promises don’t have such a feature.

  • Observables provide many operators

    There are many operators like map*,* forEach*,* filter, etc. Observables provide these whereas promises do not have any operators in their bucket.

Using Observables in JavaScript

To work with observables in JavaScript, you can either use a library like RxJS or implement your own observable using JavaScript native APIs like setTimeout, setInterval, or EventTarget. Here's an example of how to create and use an observable using RxJS:

import { Observable } from 'rxjs';

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

observable.subscribe({
  next: (value) => console.log(value),
  complete: () => console.log('Completed'),
});

Using Observables in React.js

React.js is a widely used JavaScript library for building user interfaces. It follows a declarative approach to building UIs by creating reusable components that react to changes in the application state. Integrating observables with React.js can bring substantial benefits in terms of managing state and handling asynchronous operations.

State Management with Observables

React applications often require the management of complex states, especially in applications with numerous components and dynamic data. By using observables, developers can streamline state management by representing different parts of the application state as observable streams. This enables components to subscribe to relevant streams and automatically update when the state changes.

For example, imagine a real-time dashboard displaying stock prices. Using observables, you could create an observable stream for each stock's price. Components responsible for displaying these prices can then subscribe to the corresponding observables. Whenever a stock price changes, the observables emit new values, and the subscribed components automatically update to reflect the latest prices.

Creating Responsive User Interfaces

One of the primary goals of using observables in React.js is to create responsive and real-time user interfaces. Observables enable developers to react to changes in data streams and update the UI accordingly. This is particularly useful in scenarios where real-time updates are crucial, such as chat applications, live notifications, and collaborative tools.

By subscribing to observables that represent real-time data sources, React components can be instantly updated whenever new data is emitted. This eliminates the need for manual data fetching and updating, resulting in a smoother and more interactive user experience.

Implementing Observables in React.js

To integrate observables into a React.js application, you need to install the RxJS library and import the necessary modules. You can then create observables using RxJS's Observable class and subscribe to them using the subscribe method. Additionally, RxJS provides a set of operators that allow you to manipulate, filter, and transform observables as needed.

Here's a basic example of how you can use observables in a React component:

import React, { useState, useEffect } from 'react';
import { Observable } from 'rxjs';

const StockPriceComponent = () => {
  const [stockPrice, setStockPrice] = useState(null);

  useEffect(() => {
    const stockPriceObservable = new Observable((observer) => {
      // Simulate fetching stock prices from an API
      setInterval(() => {
        const price = /* fetch stock price */;
        observer.next(price);
      }, 1000);
    });

    const subscription = stockPriceObservable.subscribe((price) => {
      setStockPrice(price);
    });

    return () => {
      subscription.unsubscribe();
    };
  }, []);

  return (
    <div>
      <h2>Stock Price</h2>
      <p>{stockPrice}</p>
    </div>
  );
};

export default StockPriceComponent;

In this example, the stockPriceObservable emits a new price every second, which is then displayed in the component. Remember that this is a simplified example; in a real application, you would likely integrate observables with more complex state management and asynchronous workflows.

Conclusion

In the ever-evolving landscape of web development, embracing observables is akin to unlocking a new dimension of efficiency and reactivity. We've journeyed through the fundamentals of observables, discovering how they empower us to seamlessly manage asynchronous data and events in our applications.

When integrated with React.js, observables become a dynamic duo, transforming the way we handle state management, asynchronous operations, and responsive user interfaces. The synergy between these two technologies has the potential to elevate your web development projects to new heights.

Your turn

Now that you've embarked on this exploration of observables and their integration with React.js, it's time to roll up your sleeves and put this knowledge into practice. Here are some steps you can take:

  1. Experiment with Observables: Start by experimenting with observables in your React applications. Identify areas where real-time updates, complex state management, or asynchronous tasks can benefit from observables.

  2. Explore RxJS: If you haven't already, dive deeper into RxJS, the library that brings observables to life in JavaScript. Explore its extensive set of operators to master the art of data manipulation and transformation.

  3. Collaborate and Learn: Engage with the development community. Join forums, discussion groups, or online communities where developers share their experiences and solutions with observables and React.js.

  4. Stay Updated: Keep an eye on updates and best practices in the world of observables and React.js. Technology evolves rapidly, and staying informed will help you harness the full potential of these tools.

  5. Apply in Real Projects: Take on projects that challenge you to apply observables and React.js in real-world scenarios. The hands-on experience will solidify your understanding and open doors to innovative solutions.

As you embark on this journey, remember that observables and React.js are tools that adapt to your creativity. They empower you to build not just functional but delightful web applications that respond to the demands of the modern digital world. So, go ahead, create, innovate, and craft web experiences that leave a lasting impact. Happy coding!

Did you find this article valuable?

Support Utkarsh by becoming a sponsor. Any amount is appreciated!