0
0
AngularConceptBeginner · 3 min read

What is Subject in RxJS: Explanation and Example

In RxJS, a Subject is a special type of observable that allows values to be multicasted to many observers. It acts both as an observable and an observer, meaning you can emit new values and subscribe to them. This makes Subject useful for sharing data or events between different parts of an Angular app.
⚙️

How It Works

Think of a Subject as a radio station broadcasting music. The station (Subject) sends out signals (values), and many radios (observers) can tune in to listen at the same time. Unlike a regular observable that creates a new stream for each listener, a Subject shares the same stream with all listeners.

It works both ways: you can send data into the Subject, and it will pass that data to all subscribers. This is like a group chat where anyone can send a message, and everyone in the chat sees it immediately.

💻

Example

This example shows how to create a Subject, subscribe two observers to it, and emit values that both observers receive.

typescript
import { Subject } from 'rxjs';

const subject = new Subject<number>();

subject.subscribe(value => console.log('Observer 1:', value));
subject.subscribe(value => console.log('Observer 2:', value));

subject.next(10);
subject.next(20);
Output
Observer 1: 10 Observer 2: 10 Observer 1: 20 Observer 2: 20
🎯

When to Use

Use a Subject when you want to share data or events between multiple parts of your Angular app without creating separate streams for each listener. For example:

  • Sharing user input or events across components
  • Implementing a simple event bus for communication
  • Multicasting data from a single source to many subscribers

Subjects are great for real-time updates where many parts of your app need to react to the same data changes.

Key Points

  • A Subject is both an observable and an observer.
  • It multicasts values to multiple subscribers.
  • You can emit new values using next().
  • Useful for sharing data or events across components.
  • Does not hold a current value like a BehaviorSubject.

Key Takeaways

A Subject lets you multicast values to many subscribers at once.
It acts as both a data producer and consumer in RxJS.
Use Subjects to share events or data across Angular components.
Emit values with next() and subscribe to receive them.
Subjects do not store the last value; use BehaviorSubject if needed.