Introduction

RxJS (Reactive Extensions for JavaScript) is a powerful library for handling asynchronous operations and events using reactive programming concepts. One of the fundamental components of RxJS is the distinction between Observable and Subject. While both play a crucial role in managing streams of data, they have distinct characteristics and use cases. In this article, we’ll delve into the key differences between Observable and Subject in RxJS.

The YouTube Channels in both English (En) and French (Fr) are now accessible, feel free to subscribe by clicking here.

RxJS Observable

At the core of RxJS is the concept of Observable, which represents a stream of values over time. An Observable is a blueprint for creating a data stream and defining how to react to the events emitted by that stream. Observables are often used to model asynchronous operations, such as HTTP requests, user interactions, or any sequence of events.

Characteristics of Observables

  1. Unicast: Observables are unicast by default, meaning each subscribed observer gets its independent execution of the Observable. This makes them suitable for handling multiple subscribers, each receiving its own copy of the data.
  2. Cold: Observables are considered “cold” because the data stream is created anew for each subscriber. When a new observer subscribes, it triggers the execution of the Observable sequence from the beginning.
  3. Immutable: Once an Observable is created, its internal state remains immutable (stateless). You can’t push new values into an existing Observable; instead, you create a new Observable instance.

Create an RxJS Observable

import { Observable } from 'rxjs';

// Create an Observable that emits values 1, 2, and 3 over time
const observable = new Observable<number>((observer) => {
  observer.next(1);
  observer.next(2);
  observer.next(3);
  observer.complete();
});

// Subscribe to the Observable
observable.subscribe({
  next: (value) => console.log(`Observer A: ${value}`),
  complete: () => console.log('Observer A: Completed'),
});

// Subscribe again to the same Observable
observable.subscribe({
  next: (value) => console.log(`Observer B: ${value}`),
  complete: () => console.log('Observer B: Completed'),
});

There are many playground environments to test your RxJS code online, I used PlayCode and the output looks like this:

Sample RxJS Observable Output

RxJS Subject

Subjects, on the other hand, act as both an Observer and an Observable. They are more versatile and allow for imperatively pushing values into the Observable execution. Subjects are like event emitters that maintain a list of observers and can multicast data to all subscribed observers.

Characteristics of Subjects

  1. Multicast: Subjects are multicast by nature, allowing multiple observers to subscribe to the same Subject and share the same execution. When a Subject emits a value, all subscribers receive the update.
  2. Hot: Subjects are considered “hot” because they are always producing values, regardless of whether there are subscribers. If an observer subscribes late, it might miss some or all of the previous emissions.
  3. Mutable: Subjects are mutable and allow you to imperatively push new values into the stream using methods like "next()". This makes them a great choice for scenarios where you need more control over the data flow.

Create an RxJS Subject

import { Subject } from 'rxjs';

// Create a Subject
const subject = new Subject<number>();

// Subscribe to the Subject
subject.subscribe({
  next: (value) => console.log(`Subject A: ${value}`),
  complete: () => console.log('Subject A: Completed'),
});

// Push values into the Subject
subject.next(1);
subject.next(2);
subject.next(3);

// Subscribe again to the same Subject
subject.subscribe({
  next: (value) => console.log(`Subject B: ${value}`),
  complete: () => console.log('Subject B: Completed'),
});

// Push more values into the Subject
subject.next(4);
subject.next(5);

// Complete the Subject
subject.complete();

The output should be similar to the following:

Sample RxJS Subject Output

Choosing Between Observable and Subject in RxJS

The choice between Observable and Subject depends on the requirements of your application:

  • Use Observables when you need a new and independent execution of the stream for each subscriber. This is suitable for scenarios where you want subscribers to receive the entire sequence of events from the beginning.
  • Use Subjects when you need to share the same execution of the stream among multiple subscribers, and when you want more control over pushing new values into the stream. Subjects are ideal for scenarios where you need to maintain state or broadcast events to multiple observers.

You may also be interested in the Difference between RxJS Observable, Subject, and BehaviorSubject that we published in the past.

———————

We have just started our journey to build a network of professionals to grow even more our free knowledge-sharing community that will give you a chance to learn interesting things about topics like cloud computing, software development, and software architectures while keeping the door open to more opportunities.

Does this speak to you? If YES, feel free to Join our Discord Server to stay in touch with the community and be part of independently organized events.

———————

Conclusion

In conclusion, both Observable and Subject are essential constructs in the RxJS toolbox, each serving distinct purposes. Understanding their characteristics and use cases is crucial for effective reactive programming and building scalable, maintainable applications. By mastering the difference between Observable and Subject, you’ll be better equipped to design reactive systems that elegantly handle complex asynchronous scenarios.

Thanks for reading this article. Like, recommend, and share if you enjoyed it. Follow us on Facebook, Twitter, and LinkedIn for more content.

author-avatar

About Orleando Dassi

I'm a Solutions Architect with 10 years of experience who is constantly learning while impacting the community by producing technical articles/videos, building projects, and conducting tech mentoring/coaching sessions. What describes me the most is my flexibility. Follow me on Twitter and LinkedIn.