Explain it simply
Subject & BehaviorSubject, in plain language
Subject is both an Observable and an Observer. BehaviorSubject stores its current value and immediately hands it to new subscribers.
Problem → Why → Solution
The problem — why this concept matters
Exposing a public Subject that every component can next into removes control over state transitions.
A common mistake
One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.
Core concept — understand how it works
A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.
- input and state
- component and template
- rendered Angular UI
Explain the core concept and Angular data flow of Subject & BehaviorSubject
Core syntax or pattern
import { Subject, BehaviorSubject } from 'rxjs';
// Subject - simple event bus
const subject = new Subject<string>();
subject.subscribe(val => console.log('Subscriber 1:', val));
subject.next('Hello'); // Subscriber 1: Hello
subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next('World'); // Both subscribers receive 'World'
// BehaviorSubject - has initial value, remembers last value
const behaviorSubject = new BehaviorSubject<number>(0);
behaviorSubject.subscribe(val => console.log('Sub A:', val)); // Sub A: 0
behaviorSubject.next(1); // Sub A: 1
// New subscriber gets last value immediately
behaviorSubject.subscribe(val => console.log('Sub B:', val)); // Sub B: 1
// Real example: Shared state service
@Injectable({ providedIn: 'root' })
export class UserStateService {
private userSubject = new BehaviorSubject<User | null>(null);
user$ = this.userSubject.asObservable();
setUser(user: User) {
this.userSubject.next(user);
}
}A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.
Read the code step by step
- input and state
import { Subject, BehaviorSubject } from 'rxjs';Subject is both an Observable and an Observer. BehaviorSubject stores its current value and immediately hands it to new subscribers.
- component and template
// New subscriber gets last value immediatelyA Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.
- rendered Angular UI
}Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.
- input and state
- component and template
- rendered Angular UI
Success
Explain the core concept and Angular data flow of Subject & BehaviorSubject
Failure
Exposing a public Subject that every component can next into removes control over state transitions.
Subject is both an Observable and an Observer. BehaviorSubject stores its current value and immediately hands it to new subscribers.
import { Subject, BehaviorSubject } from 'rxjs';
// Subject - simple event bus
const subject = new Subject<string>();
subject.subscribe(val => console.log('Subscriber 1:', val));
subject.next('Hello'); // Subscriber 1: Hello
subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next('World'); // Both subscribers receive 'World'
// BehaviorSubject - has initial value, remembers last value
const behaviorSubject = new BehaviorSubject<number>(0);
behaviorSubject.subscribe(val => console.log('Sub A:', val)); // Sub A: 0
behaviorSubject.next(1); // Sub A: 1
// New subscriber gets last value immediately
behaviorSubject.subscribe(val => console.log('Sub B:', val)); // Sub B: 1
// Real example: Shared state service
@Injectable({ providedIn: 'root' })
export class UserStateService {
private userSubject = new BehaviorSubject<User | null>(null);
user$ = this.userSubject.asObservable();
setUser(user: User) {
this.userSubject.next(user);
}
}(Subject/BehaviorSubject can be used to share data between components)Real-world usage
How to apply it in a real project
Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.
Mini challenge
Build it yourself
Rebuild the Subject & BehaviorSubject example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.
- Rebuild the example without copying it
- Test a normal input and an edge case
- Predict the compiler or output result before running it
import { Subject, BehaviorSubject } from 'rxjs';
// Subject - simple event bus
const subject = new Subject<string>();
subject.subscribe(val => console.log('Subscriber 1:', val));
subject.next('Hello'); // Subscriber 1: Hello
subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next('World'); // Both subscribers receive 'World'
// BehaviorSubject - has initial value, remembers last value
const behaviorSubject = new BehaviorSubject<number>(0);
behaviorSubject.subscribe(val => console.log('Sub A:', val)); // Sub A: 0
behaviorSubject.next(1); // Sub A: 1
// New subscriber gets last value immediately
behaviorSubject.subscribe(val => console.log('Sub B:', val)); // Sub B: 1
// Real example: Shared state service
@Injectable({ providedIn: 'root' })
export class UserStateService {
private userSubject = new BehaviorSubject<User | null>(null);
user$ = this.userSubject.asObservable();
setUser(user: User) {
this.userSubject.next(user);
}
}Expected: Explain the core concept and Angular data flow of Subject & BehaviorSubject
Show hint
Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.
Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- input and state → component and template → rendered Angular UI
- A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.
- Exposing a public Subject that every component can next into removes control over state transitions.
- Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.
RxJS — Guide — RxJS