Suggest an editImprove this articleRefine the answer for “What is ReplaySubject?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**ReplaySubject** is a type of `Subject` in RxJS that **remembers several of the latest values and replays them to new subscribers**. **Key point:** the number of stored values is set in the constructor.Shown above the full answer for quick recall.Answer (EN)ImageLet's continue in the same format. --- ## Briefly (as in an interview) **ReplaySubject** is a type of `Subject` in RxJS that **remembers several of the latest values and replays them to new subscribers**. The number of stored values is set in the constructor. --- ## In detail `ReplaySubject` is an extension of `Subject` that **buffers previous values** and **replays them** on a new subscription. Example: ```ts import { ReplaySubject } from 'rxjs'; const subject = new ReplaySubject<number>(2); subject.next(1); subject.next(2); subject.next(3); subject.subscribe(v => console.log(v)); ``` Result: ``` 2 3 ``` Because the buffer is set to **2 values**. --- ### Constructor ```ts new ReplaySubject<T>(bufferSize?, windowTime?) ``` Parameters: - `bufferSize` - how many values to store - `windowTime` - how long to store values Example with time: ```ts new ReplaySubject(3, 5000) ``` Stores: - a maximum of 3 values - no older than 5 seconds --- ## Difference from BehaviorSubject | Type | Stores values | Initial value | New subscriber gets | |---|---|---|---| | Subject | No | No | nothing | | BehaviorSubject | 1 | required | the latest value | | ReplaySubject | N | not required | the last N | The main difference: - BehaviorSubject = **current state** - ReplaySubject = **history** --- ## When ReplaySubject is used Less often than BehaviorSubject. For example: - caching events - event history - logging streams - state rehydration - event bus Example of an event system: ```ts events$ = new ReplaySubject<AppEvent>(10); ``` --- ## An important point (often asked) ReplaySubject **can lead to memory leaks** if: - the buffer is large - the stream is long-lived - the values are heavy That's why the buffer is almost always limited. --- ## A typical follow-up question In an interview you might be asked: **Why is BehaviorSubject used more often in Angular?** Answer: Because Angular state is usually a **current value**, not a history.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.