Hack Frontend Community

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:

TypeStores value?What new subscriber gets
SubjectNoOnly new values after subscription
BehaviorSubjectYes (only last)Immediately gets last value
ReplaySubjectYes (all or part)Gets all/several past values
AsyncSubjectYes (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?

ScenarioSubject
Event stream (e.g., buttons)Subject
State storageBehaviorSubject
Message or log historyReplaySubject
Only result after operation completionAsyncSubject

Tip:

In Angular BehaviorSubject is most often used for managing component and service state, as it guarantees current value on subscription.