Discover how Angular Subjects keep your app's data flowing smoothly to everyone, anytime!
Why Subject types (Subject, BehaviorSubject, ReplaySubject) in Angular? - Purpose & Use Cases
Imagine you have a group chat where you want to share messages with friends. You try to tell each friend the messages one by one as they come in, but if a friend joins late, they miss all the earlier messages.
Manually tracking who joined and what messages they missed is confusing and easy to mess up. You might forget to send old messages or accidentally send duplicates. This makes your chat unreliable and frustrating.
Angular's Subject types like Subject, BehaviorSubject, and ReplaySubject handle message sharing smoothly. They automatically manage who gets what messages, even if they join late, so you never miss important updates.
let subscribers = [];
function sendMessage(msg) {
subscribers.forEach(sub => sub(msg));
}
function subscribe(sub) {
subscribers.push(sub);
// no way to send old messages
}import { BehaviorSubject } from 'rxjs'; const subject = new BehaviorSubject('Welcome'); subject.subscribe(msg => console.log(msg)); subject.next('New message');
It enables easy, reliable sharing of data streams with multiple listeners, ensuring everyone stays updated no matter when they join.
Think of a live sports score app where fans join anytime. BehaviorSubject makes sure new fans see the current score immediately, while ReplaySubject can show the last few plays so no one feels lost.
Subjects help share data streams with many listeners.
BehaviorSubject remembers the latest value for new subscribers.
ReplaySubject replays a set number of past values to new subscribers.
Practice
Solution
Step 1: Understand BehaviorSubject behavior
BehaviorSubject stores the last emitted value and sends it immediately to any new subscriber.Step 2: Compare with other Subjects
Subject sends only to current subscribers without remembering past values. ReplaySubject replays multiple past values, not just the last one.Final Answer:
BehaviorSubject -> Option BQuick Check:
Last value sent immediately = BehaviorSubject [OK]
- Confusing ReplaySubject with BehaviorSubject
- Thinking Subject remembers past values
- Assuming AsyncSubject behaves like BehaviorSubject
Solution
Step 1: Check ReplaySubject constructor
ReplaySubject takes a number argument specifying how many past values to store and replay.Step 2: Validate options
new ReplaySubject(3) correctly passes number 3. new ReplaySubject() uses no argument (defaults to unlimited or 1 depending on implementation). new ReplaySubject(1) stores only 1 value. new ReplaySubject('3') passes a string, which is invalid.Final Answer:
new ReplaySubject(3) -> Option CQuick Check:
ReplaySubject(3) stores last 3 values [OK]
- Passing string instead of number to ReplaySubject
- Omitting the buffer size argument
- Confusing ReplaySubject with BehaviorSubject constructor
const subject = new BehaviorSubject('start');
subject.next('first');
subject.subscribe(value => console.log('Subscriber 1:', value));
subject.next('second');
subject.subscribe(value => console.log('Subscriber 2:', value));What will be printed to the console?
Solution
Step 1: Trace BehaviorSubject emissions
BehaviorSubject starts with 'start', then next emits 'first'. Subscriber 1 subscribes after 'first', so it receives the last value 'first' immediately, then 'second' when emitted.Step 2: Analyze Subscriber 2 subscription
Subscriber 2 subscribes after 'second' is emitted, so it immediately receives 'second'.Final Answer:
Subscriber 1: start
Subscriber 1: first
Subscriber 1: second
Subscriber 2: second -> Option AQuick Check:
BehaviorSubject sends last value on subscribe [OK]
- Assuming Subscriber 2 gets 'first' value
- Ignoring initial 'start' emission to Subscriber 1
- Ignoring immediate emission on subscription
const subject = new Subject();
subject.next('hello');
subject.subscribe(value => console.log(value));Solution
Step 1: Understand Subject behavior
Subject sends values only to current subscribers. Since next('hello') is called before subscribe, no subscriber receives it.Step 2: Check for errors
There is no syntax or runtime error. The code runs but subscriber misses the first value.Final Answer:
The subscription will not receive 'hello' because Subject does not replay past values. -> Option AQuick Check:
Subject sends only to current subscribers [OK]
- Expecting subscriber to get values emitted before subscription
- Thinking next() before subscribe causes error
- Confusing Subject with BehaviorSubject or ReplaySubject
Solution
Step 1: Identify requirement for storing multiple past messages
BehaviorSubject stores only the last single value, so it cannot replay two messages automatically.Step 2: Choose Subject type that replays multiple past values
ReplaySubject with buffer size 2 stores and replays last 2 messages automatically to new subscribers.Step 3: Evaluate other options
Subject does not store past messages. ReplaySubject(1) stores only one message, not two.Final Answer:
Use ReplaySubject(2) to store and replay last 2 messages to new subscribers. -> Option DQuick Check:
ReplaySubject(n) replays last n messages [OK]
- Using BehaviorSubject to store multiple past messages
- Assuming Subject stores past messages
- Setting ReplaySubject buffer size too low
Ready to prove it?
Pass the test and this pattern moves unknown
