RxJS Subjects
Learn what RxJS Subjects are, how they work as both Observables and Observers, and how Subject types can be used for sharing and distributing values.
What is a Subject?
A Subject is a special type of RxJS Observable that can also receive values.
Unlike a normal Observable where values are generally produced by the Observable source, a Subject allows application code to call methods such as next() and send values to its subscribers.
A Subject can therefore act as both an Observable and an Observer.
Subject Working Flow
Subject as Observable and Observer
As Observable
Other parts of the application can subscribe to the Subject.
As Receiver
The Subject can receive values through next().
Multicast
One emitted value can be delivered to multiple subscribers.
Shared Stream
Multiple consumers can observe the same Subject stream.
Creating a Subject
import { Subject } from '@rxjs';
const courseSubject =
new Subject<string>();
Subscribing to a Subject
A Subject can have multiple subscribers.
When the Subject emits a value using next(), each active subscriber receives that value.
courseSubject.subscribe({
next: course => {
console.log(
'Subscriber 1:',
course
);
}
});
courseSubject.subscribe({
next: course => {
console.log(
'Subscriber 2:',
course
);
}
});
Emitting Values with next()
courseSubject.next(
'Java Full Stack'
);
courseSubject.next(
'.NET Full Stack'
);
courseSubject.next(
'Python Full Stack'
);
Subject Output
Subscriber 1: Java Full Stack
Subscriber 2: Java Full Stack
Subscriber 1: .NET Full Stack
Subscriber 2: .NET Full Stack
Both active subscribers receive each emitted value.
Subject and Multicasting
A Subject can multicast a value to multiple subscribers.
When the Subject emits a value, all subscribers that are currently connected to the Subject receive that emission.
Late Subscribers
A normal Subject does not automatically replay values that were emitted before a subscriber joined.
This is an important difference between a regular Subject and subjects such as BehaviorSubject and ReplaySubject.
const subject =
new Subject<string>();
subject.next(
'Java Full Stack'
);
subject.subscribe({
next: value => {
console.log(value);
}
});
subject.next(
'.NET Full Stack'
);
Output
.NET Full Stack
BehaviorSubject
A BehaviorSubject requires an initial value and stores the latest emitted value.
A new subscriber immediately receives the current value when it subscribes.
import {
BehaviorSubject
} from '@rxjs';
const courseSubject =
new BehaviorSubject<string>(
'Angular'
);
courseSubject.subscribe({
next: course => {
console.log(course);
}
});
Initial Value
Angular
Updating BehaviorSubject
const courseSubject =
new BehaviorSubject<string>(
'Angular'
);
courseSubject.next(
'React'
);
courseSubject.next(
'Node.js'
);
The latest emitted value remains available as the current value for future subscribers.
ReplaySubject
A ReplaySubject can replay previously emitted values to a new subscriber according to the configured buffer.
It is useful when a subscriber needs access to recent values that were emitted before the subscription started.
import {
ReplaySubject
} from '@rxjs';
const courseSubject =
new ReplaySubject<string>(2);
courseSubject.next(
'Java'
);
courseSubject.next(
'.NET'
);
courseSubject.next(
'Python'
);
courseSubject.subscribe({
next: course => {
console.log(course);
}
});
Replayed Values
.NET
Python
AsyncSubject
An AsyncSubject emits the latest value to subscribers only when the Subject completes.
If the Subject completes without emitting a value, no value is delivered to subscribers.
import {
AsyncSubject
} from '@rxjs';
const resultSubject =
new AsyncSubject<number>();
resultSubject.subscribe({
next: value => {
console.log(value);
}
});
resultSubject.next(10);
resultSubject.next(20);
resultSubject.next(30);
resultSubject.complete();
Output
30
Types of RxJS Subjects
Subject
Multicasts values to current subscribers.
BehaviorSubject
Stores and emits the current value to new subscribers.
ReplaySubject
Replays previously emitted values according to its buffer.
AsyncSubject
Emits the latest value when the Subject completes.
Subject Types Comparison
| Subject Type | Initial Value | New Subscriber Receives | Main Feature |
|---|---|---|---|
| Subject | Not required | Future emissions | Multicast current values |
| BehaviorSubject | Required | Current/latest value | Stores current value |
| ReplaySubject | Not required | Buffered previous values | Replays values |
| AsyncSubject | Not required | Latest value after completion | Final-value emission |
Subject vs Observable
| Feature | Observable | Subject |
|---|---|---|
| Can Subscribe | Yes | Yes |
| Can Call next() | Not from the consumer API | Yes |
| Multiple Subscribers | Depends on the source and sharing strategy | Yes, values are multicasted |
| Manual Emission | Source controls emissions | next() can emit values |
| Special Variants | No Subject-specific variants | BehaviorSubject, ReplaySubject, AsyncSubject |
CIIT Training Institute Example
Suppose the CIIT Training Institute application has a selected-course stream that is used by multiple components.
A BehaviorSubject can store the current selected course so that subscribers can receive the latest value.
import {
BehaviorSubject
} from '@rxjs';
export class CourseStateService {
private selectedCourseSubject =
new BehaviorSubject<string>(
'Java Full Stack'
);
selectedCourse$ =
this.selectedCourseSubject
.asObservable();
selectCourse(course: string) {
this.selectedCourseSubject
.next(course);
}
}
this.courseStateService
.selectedCourse$
.subscribe({
next: course => {
console.log(
'Selected Course:',
course
);
}
});
CIIT Training Institute
Selected Course: Java Full Stack
Other components can subscribe to the shared course state.
Using asObservable()
A Subject can expose an Observable view using asObservable().
This is useful when other parts of the application should subscribe to a stream without directly calling next() on the underlying Subject.
private courseSubject =
new BehaviorSubject<string>(
'Java Full Stack'
);
course$ =
this.courseSubject
.asObservable();
Subject Lifecycle
complete() and error()
const subject =
new Subject<string>();
subject.subscribe({
next: value => {
console.log(value);
},
error: error => {
console.error(error);
},
complete: () => {
console.log(
'Completed'
);
}
});
subject.next('Angular');
subject.complete();
After a Subject has completed or errored, it cannot continue its normal emission lifecycle.
When Can Subjects Be Useful?
Shared State
Share a value or state stream between multiple consumers.
Events
Represent application events that multiple consumers need.
Notifications
Broadcast application notifications to subscribers.
Communication
Coordinate communication between services and consumers.
Avoid Unnecessary Subjects
Subjects are useful, but every Observable-based problem does not require a Subject.
When data can be represented cleanly using a normal Observable pipeline, introducing a Subject may add unnecessary state or lifecycle complexity.
RxJS Subject Best Practices
- Use Subject when the application genuinely needs manual emission or multicasting behavior.
- Use BehaviorSubject when a current value needs to be retained and made available to new subscribers.
- Use ReplaySubject when recent past values need to be replayed.
- Keep Subjects private inside services when external consumers only need to observe the stream.
-
Expose a read-only Observable using
asObservable()where appropriate. - Avoid using Subjects everywhere when a normal Observable pipeline provides a simpler solution.
Important Points
A Subject exposes methods such as next() that can be used to emit values.
Active subscribers receive the values emitted by the Subject.
BehaviorSubject, ReplaySubject and AsyncSubject are designed for different value-delivery requirements.
Keeping a Subject private and exposing an Observable view can provide better control over who can emit values.
Summary
A Subject is an RxJS type that can act as both an Observable and an Observer.
BehaviorSubject stores the current value, ReplaySubject can replay buffered values, and AsyncSubject emits its latest value when it completes.
Subjects are useful for multicasting and shared reactive state, but they should be introduced only when their behavior is actually required. The RxJS module is now complete .