RxJS & Reactive Programming
Angular Subject and BehaviorSubject
A Subject is both an Observable and an observer: you can subscribe to it and also push values into it with next(). BehaviorSubject additionally stores the current value and replays it to every new subscriber.
What is Subject and BehaviorSubject in Angular?
A Subject is both an Observable and an observer: you can subscribe to it and also push values into it with next(). BehaviorSubject additionally stores the current value and replays it to every new subscriber.
Subject and BehaviorSubject example
@Injectable({ providedIn: 'root' })
export class CartService {
private itemsSubject = new BehaviorSubject<Job[]>([]);
items$ = this.itemsSubject.asObservable();
get items(): Job[] { return this.itemsSubject.value; }
add(job: Job): void {
this.itemsSubject.next([...this.items, job]);
}
}Key points to remember
- BehaviorSubject for current state; Subject for one-off events.
- Expose it with asObservable() so consumers cannot push values.
- Signals now cover many BehaviorSubject use cases with less ceremony.
Subject variants
| Type | Replays | Needs an initial value |
|---|---|---|
| Subject | nothing | no |
| BehaviorSubject | the latest value | yes |
| ReplaySubject(n) | the last n values | no |
| AsyncSubject | the final value, on complete | no |
Common mistakes with Subject and BehaviorSubject
- Using Subject for state and finding that late subscribers see nothing.
- Reading .value everywhere instead of subscribing, which loses reactivity.
Angular Subject and BehaviorSubject— Interview Questions & FAQs
What is the difference between Subject and BehaviorSubject?+
A Subject emits only to subscribers present at the time of emission. A BehaviorSubject holds the most recent value and immediately replays it to every new subscriber, which is what makes it suitable for state.
