ReplaySubject in RxJS: What It Is and How It Works
ReplaySubject in RxJS is a special type of observable that stores a buffer of emitted values and replays them to new subscribers. It ensures that new subscribers receive past values immediately, not just future ones.How It Works
Imagine you are at a party where a storyteller shares stories one by one. If you arrive late, you miss the earlier stories. A ReplaySubject acts like a friend who remembers the last few stories and tells them to you as soon as you arrive, so you catch up quickly.
Technically, ReplaySubject keeps a buffer of the last emitted values (like the last few stories). When a new subscriber joins, it immediately receives all buffered values before getting new ones. This way, no subscriber misses important past data.
You can control how many past values to keep and for how long, making ReplaySubject flexible for different needs.
Example
This example shows a ReplaySubject that stores the last 2 values. When a new subscriber joins, it immediately receives those last 2 values before any new ones.
import { ReplaySubject } from 'rxjs'; const replaySubject = new ReplaySubject(2); // buffer size 2 replaySubject.next('First'); replaySubject.next('Second'); replaySubject.next('Third'); // Subscriber 1 subscribes and gets last 2 values: 'Second', 'Third' replaySubject.subscribe(value => console.log('Subscriber 1:', value)); replaySubject.next('Fourth'); // Subscriber 2 subscribes and gets last 2 values: 'Third', 'Fourth' replaySubject.subscribe(value => console.log('Subscriber 2:', value));
When to Use
Use ReplaySubject when you want new subscribers to get recent past values immediately, not just future updates. This is helpful in cases like:
- Sharing the latest user settings or configuration across components.
- Replaying recent chat messages to users who just opened the chat window.
- Caching API responses so new subscribers get data without waiting for a new request.
It is especially useful in Angular apps where multiple components need consistent shared data streams.
Key Points
ReplaySubjectstores a buffer of past values and replays them to new subscribers.- You can set how many past values to keep and how long to keep them.
- It helps late subscribers catch up with important past data immediately.
- Useful for shared data streams and caching in Angular applications.
Key Takeaways
ReplaySubject replays past emitted values to new subscribers immediately.