Using Subject Types in Angular: Subject, BehaviorSubject, ReplaySubject
📖 Scenario: You are building a simple Angular app that shares messages between components using different types of Subjects.This helps you understand how Subject, BehaviorSubject, and ReplaySubject work differently in real apps.
🎯 Goal: Create an Angular standalone component that sets up three different Subjects: Subject, BehaviorSubject, and ReplaySubject.Send messages through each and subscribe to show how they behave differently.
📋 What You'll Learn
Create a Subject called simpleSubject.
Create a BehaviorSubject called behaviorSubject with initial value 'Initial'.
Create a ReplaySubject called replaySubject with buffer size 2.
Subscribe to each subject and store the latest message in separate variables.
Send at least two messages to each subject.
Display the latest messages from each subject in the component template.
💡 Why This Matters
🌍 Real World
Sharing data reactively between components in Angular apps, such as user input, notifications, or live updates.
💼 Career
Understanding Subjects is essential for Angular developers to manage asynchronous data streams and component communication effectively.
Progress0 / 4 steps
1
Set up Subjects in the component
In the Angular component class, import Subject, BehaviorSubject, and ReplaySubject from rxjs. Then create three properties: simpleSubject as a new Subject<string>(), behaviorSubject as a new BehaviorSubject<string>('Initial'), and replaySubject as a new ReplaySubject<string>(2).
Angular
Hint
Remember to import Subject, BehaviorSubject, and ReplaySubject from rxjs and create each as a class property.
2
Add variables to hold latest messages
Add three string properties to the component class: simpleMessage, behaviorMessage, and replayMessage. Initialize each with an empty string ''.
Angular
Hint
These variables will store the latest message received from each subject.
3
Subscribe to subjects and send messages
In the component constructor, subscribe to simpleSubject, behaviorSubject, and replaySubject. For each subscription, update the corresponding message variable (simpleMessage, behaviorMessage, replayMessage) with the received value. Then send two messages to each subject: 'First' and 'Second'.
Angular
Hint
Subscribe to each subject and update the message variables inside the subscription callback. Then send two messages to each subject using next().
4
Display latest messages in the template
In the component template, add three paragraphs showing the latest messages from each subject. Use interpolation to display simpleMessage, behaviorMessage, and replayMessage with labels: Simple Subject:, Behavior Subject:, and Replay Subject: respectively.
Angular
Hint
Use interpolation {{ variable }} inside paragraph tags to show each message with a label.
Practice
(1/5)
1. Which type of Subject in Angular immediately sends the last emitted value to new subscribers?
easy
A. AsyncSubject
B. BehaviorSubject
C. ReplaySubject
D. Subject
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 B
Quick Check:
Last value sent immediately = BehaviorSubject [OK]
Hint: BehaviorSubject always sends last value to new subscribers [OK]
Common Mistakes:
Confusing ReplaySubject with BehaviorSubject
Thinking Subject remembers past values
Assuming AsyncSubject behaves like BehaviorSubject
2. Which of the following is the correct way to create a ReplaySubject that stores the last 3 values?
easy
A. new ReplaySubject(1)
B. new ReplaySubject()
C. new ReplaySubject(3)
D. new ReplaySubject('3')
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 C
Quick Check:
ReplaySubject(3) stores last 3 values [OK]
Hint: ReplaySubject(n) stores last n values for new subscribers [OK]
Common Mistakes:
Passing string instead of number to ReplaySubject
Omitting the buffer size argument
Confusing ReplaySubject with BehaviorSubject constructor
A. Subscriber 1: start Subscriber 1: first Subscriber 1: second Subscriber 2: second
B. Subscriber 1: first Subscriber 1: second Subscriber 2: first Subscriber 2: second
C. Subscriber 1: first Subscriber 1: second Subscriber 2: second
D. Subscriber 1: start Subscriber 1: second Subscriber 2: start Subscriber 2: second
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 A
Quick Check:
BehaviorSubject sends last value on subscribe [OK]
Hint: BehaviorSubject sends last value immediately on subscribe [OK]
Common Mistakes:
Assuming Subscriber 2 gets 'first' value
Ignoring initial 'start' emission to Subscriber 1
Ignoring immediate emission on subscription
4. What is wrong with this code snippet?
const subject = new Subject();
subject.next('hello');
subject.subscribe(value => console.log(value));
medium
A. The subscription will not receive 'hello' because Subject does not replay past values.
B. The code will throw a syntax error because subscribe is called after next.
C. The Subject should be replaced with BehaviorSubject to avoid errors.
D. The next() method cannot be called before any subscribers exist.
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 A
Quick Check:
Subject sends only to current subscribers [OK]
Hint: Subject does not replay values to late subscribers [OK]
Common Mistakes:
Expecting subscriber to get values emitted before subscription
Thinking next() before subscribe causes error
Confusing Subject with BehaviorSubject or ReplaySubject
5. You want to create a message service that stores the last 2 messages and sends them to any new subscriber immediately. Which Subject type and setup should you use?
hard
A. Use ReplaySubject(1) and call next() twice to replay last 2 messages.
B. Use BehaviorSubject with initial value and call next() twice to store last 2 messages.
C. Use Subject and manually store last 2 messages in an array to send on subscribe.
D. Use ReplaySubject(2) to store and replay last 2 messages to new subscribers.
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 D
Quick Check:
ReplaySubject(n) replays last n messages [OK]
Hint: ReplaySubject(n) replays last n messages automatically [OK]
Common Mistakes:
Using BehaviorSubject to store multiple past messages
Assuming Subject stores past messages
Setting ReplaySubject buffer size too low
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.