What is Subject and What Types of Subjects Exist in RxJS?
What is Subject in RxJS?
Subject is special type of Observable that can multicast data: i.e. send values to multiple subscribers at once.
It combines properties of Observable (emits values) and Observer (can pass values using .next()).
Features
- You initiate value passing through
.next() - Subscribers receive same data
- Allows centralized event stream management
Regular Subject Usage Example
import { Subject } from 'rxjs';
const subject = new Subject<string>();
subject.subscribe(val => console.log('Subscriber A:', val));
subject.subscribe(val => console.log('Subscriber B:', val));
subject.next('Hello');
// → Subscriber A: Hello
// → Subscriber B: Hello
Subject Types
RxJS provides several Subject types, which differ in behavior and value storage:
| Type | Stores value? | What new subscriber gets |
|---|---|---|
Subject | No | Only new values after subscription |
BehaviorSubject | Yes (only last) | Immediately gets last value |
ReplaySubject | Yes (all or part) | Gets all/several past values |
AsyncSubject | Yes (only final) | Gets only last when complete() |
BehaviorSubject
Used when you need subscribers to receive current value immediately on subscription.
import { BehaviorSubject } from 'rxjs';
const behavior$ = new BehaviorSubject<number>(0);
behavior$.subscribe(val => console.log('A:', val)); // A: 0
behavior$.next(1); // A: 1
behavior$.subscribe(val => console.log('B:', val)); // B: 1
Ideal for storing state (e.g., current user, application theme, etc.)
ReplaySubject
Allows "replaying" past values for new subscribers.
import { ReplaySubject } from 'rxjs';
const replay$ = new ReplaySubject<number>(2); // stores 2 last values
replay$.next(1);
replay$.next(2);
replay$.next(3);
replay$.subscribe(val => console.log('Subscriber:', val));
// → Subscriber: 2
// → Subscriber: 3
AsyncSubject
Emits only last value — only when stream is completed (complete())
import { AsyncSubject } from 'rxjs';
const async$ = new AsyncSubject<number>();
async$.subscribe(val => console.log('Result:', val));
async$.next(1);
async$.next(2);
async$.next(3);
async$.complete(); // → Result: 3
Used for deferred values, for example, when making one-time data request
When to Use Which?
| Scenario | Subject |
|---|---|
| Event stream (e.g., buttons) | Subject |
| State storage | BehaviorSubject |
| Message or log history | ReplaySubject |
| Only result after operation completion | AsyncSubject |
Tip:
In Angular BehaviorSubject is most often used for managing component and service state, as it guarantees current value on subscription.