Angular ReplaySubject

Learn Angular ReplaySubject with RxJS including replay buffer, multicasting, event history, architecture diagrams, enterprise use cases, best practices, and interview questions.

Angular ReplaySubject - Complete Guide

ReplaySubject is a special type of RxJS Subject that stores previously emitted values and replays them to new subscribers.

Unlike a regular Subject, which only emits future values, a ReplaySubject remembers past values based on a configurable buffer size or time window.

ReplaySubject is commonly used in enterprise Angular applications for:

  • Chat History
  • Notification History
  • Audit Events
  • Application Logs
  • Live Dashboards
  • Stock Price History
  • IoT Data Streams
  • WebSocket Messages
  • Event Replay
  • Analytics

ReplaySubject is one of the most frequently asked Angular interview topics.


Table of Contents

  • What is ReplaySubject?
  • Why Use ReplaySubject?
  • ReplaySubject Architecture
  • Creating ReplaySubject
  • Buffer Size
  • Time Window
  • ReplaySubject Lifecycle
  • ReplaySubject vs Subject
  • ReplaySubject vs BehaviorSubject
  • Enterprise Banking Example
  • Performance Best Practices
  • Common Mistakes
  • Top 10 Interview Questions
  • Summary

What is ReplaySubject?

A ReplaySubject is an RxJS Subject that stores previously emitted values and replays them to new subscribers.

Unlike BehaviorSubject:

  • No initial value is required.
  • Multiple previous values can be replayed.
  • Buffer size is configurable.
  • Time window can also be configured.

ReplaySubject Architecture

flowchart TD

ReplaySubject

ReplaySubject --> Buffer

Buffer --> SubscriberA

Buffer --> SubscriberB

Buffer --> SubscriberC

Why Use ReplaySubject?

Without ReplaySubject

  • New subscribers miss previous events
  • Lost notification history
  • Components start with incomplete data
  • Difficult event synchronization

With ReplaySubject

  • Event history is preserved
  • Better user experience
  • Easier debugging
  • Improved synchronization
  • Shared historical data

Creating a ReplaySubject

import { ReplaySubject } from 'rxjs';

const subject =

new ReplaySubject<number>(3);

The number 3 represents the buffer size.

Only the latest three values are stored.


Emitting Values

subject.next(10);

subject.next(20);

subject.next(30);

subject.next(40);

subject.next(50);

Current Buffer

30

40

50

Older values are removed automatically once the buffer is full.


Replay Flow

sequenceDiagram

participant Publisher

participant ReplaySubject

participant Subscriber

Publisher->>ReplaySubject: 10

Publisher->>ReplaySubject: 20

Publisher->>ReplaySubject: 30

Publisher->>ReplaySubject: 40

Publisher->>ReplaySubject: 50

Subscriber->>ReplaySubject: Subscribe

ReplaySubject-->>Subscriber: 30

ReplaySubject-->>Subscriber: 40

ReplaySubject-->>Subscriber: 50

Buffer Size

The buffer size determines how many previous values are remembered.

Example

const prices$ =

new ReplaySubject<number>(2);

prices$.next(100);

prices$.next(200);

prices$.next(300);

New Subscriber Receives

200

300

Buffer Architecture

flowchart LR

Events

Events --> Buffer

Buffer --> LastNValues

LastNValues --> Subscriber

Time Window

ReplaySubject can also replay values emitted within a specified time period.

Example

const subject =

new ReplaySubject<string>(

100,

5000

);

Parameters

  • Buffer Size → 100
  • Window Time → 5000 ms

Only values emitted during the last 5 seconds are replayed to new subscribers.


Time Window Architecture

flowchart TD

Events

Events --> TimeWindow

TimeWindow --> ReplaySubject

ReplaySubject --> Subscriber

ReplaySubject Lifecycle

flowchart TD
    A["Create ReplaySubject"]
    B["next()"]
    C["Buffer"]
    D["Subscribe"]
    E["Replay Values"]
    F["Future Values"]

    A --> B
    B --> C
    C --> D
    D --> E
    E --> F

ReplaySubject vs Subject

Feature ReplaySubject Subject
Initial Value No No
Replay Previous Values Yes No
Buffer Size Configurable No
Multicasting Yes Yes
Typical Use History Events

ReplaySubject vs BehaviorSubject

Feature ReplaySubject BehaviorSubject
Initial Value Optional Required
Current Value Buffer Latest Value
Replay Count Multiple One
New Subscriber Buffer Values Latest Value
Best For History Shared State

Event History Example

private notificationsSubject =

new ReplaySubject<string>(5);

notifications$ =

this.notificationsSubject

.asObservable();

addNotification(

message:string

){

this.notificationsSubject

.next(message);

}

Component

this.notificationService

.notifications$

.subscribe(

message => {

console.log(message);

});

A newly opened notification panel immediately receives the most recent notifications.


Chat History Example

private chatSubject =

new ReplaySubject<Message>(20);

messages$ =

this.chatSubject.asObservable();

receiveMessage(

message: Message

){

this.chatSubject.next(message);

}

Benefits

  • Chat history
  • Better user experience
  • Supports reconnecting clients

Chat Architecture

flowchart TD

WebSocket

WebSocket --> ReplaySubject

ReplaySubject --> ChatWindow

ReplaySubject --> NotificationPanel

ReplaySubject --> MobileClient

Enterprise Banking Example

Internet Banking Dashboard

ReplaySubject Stores

  • Transaction History
  • Recent Notifications
  • Fraud Alerts
  • Market Prices
  • Exchange Rates
  • Security Events

Architecture

flowchart TD

AngularApp

AngularApp --> NotificationService

AngularApp --> TransactionService

AngularApp --> MarketService

NotificationService --> ReplaySubject

TransactionService --> ReplaySubject

MarketService --> ReplaySubject

ReplaySubject --> Dashboard

ReplaySubject --> Reports

ReplaySubject --> Alerts

Benefits

  • Event history
  • Improved auditing
  • Better customer experience
  • Real-time updates
  • Scalable architecture

ReplaySubject with WebSocket

private stockPrices =

new ReplaySubject<StockPrice>(10);

socket.onmessage = event => {

const price =

JSON.parse(event.data);

this.stockPrices.next(price);

};

Late subscribers immediately receive the latest stock price history before continuing with live updates.


Performance Best Practices

Practice Benefit
Use the smallest practical buffer Lower memory usage
Limit replay history Better performance
Prefer BehaviorSubject for current state Simpler state management
Expose asObservable() Better encapsulation
Use time windows when appropriate Automatic cleanup
Monitor memory usage Prevent excessive buffering

Common Mistakes

Using Unlimited Buffer

Avoid

new ReplaySubject();

This creates an unbounded buffer that can grow indefinitely.

Better

new ReplaySubject(10);

Using ReplaySubject for Shared State

ReplaySubject stores history.

For current application state, BehaviorSubject is often the better choice.


Large Buffer Sizes

Avoid unnecessarily large buffers.

Bad

new ReplaySubject(100000);

Large buffers consume additional memory and may reduce performance.


Exposing ReplaySubject Directly

Avoid

public messages =

new ReplaySubject<Message>(20);

Better

private messagesSubject =

new ReplaySubject<Message>(20);

messages$ =

this.messagesSubject

.asObservable();

Replaying Sensitive Data

Avoid replaying:

  • Passwords
  • Authentication Tokens
  • Credit Card Data
  • Personally Identifiable Information (PII)

Replay only data that is appropriate to retain in memory.


Best Practices

  • Choose an appropriate buffer size.
  • Use time windows for expiring history when needed.
  • Expose only Observables.
  • Keep ReplaySubjects private.
  • Use immutable objects.
  • Prefer BehaviorSubject for shared state.
  • Avoid replaying sensitive data.
  • Monitor memory consumption.
  • Write unit tests.
  • Use ReplaySubject only when replay behavior is required.

Advantages

Feature Benefit
Event Replay Historical data
Multicasting Multiple subscribers
Configurable Buffer Flexible replay
Time Window Automatic expiration
Enterprise Ready Scalable event distribution

Top 10 Angular ReplaySubject Interview Questions

1. What is ReplaySubject?

Answer

ReplaySubject is an RxJS Subject that stores previous values and replays them to new subscribers.


2. How is ReplaySubject different from Subject?

Answer

A Subject only emits future values, while a ReplaySubject also replays previously emitted values based on its buffer configuration.


3. How is ReplaySubject different from BehaviorSubject?

Answer

BehaviorSubject stores only the latest value and requires an initial value. ReplaySubject can replay multiple previous values and does not require an initial value.


4. What is the buffer size?

Answer

The buffer size defines how many previously emitted values ReplaySubject stores for future subscribers.


5. What is the time window?

Answer

The time window limits replay to values emitted within a specified duration.


6. Does ReplaySubject require an initial value?

Answer

No. Unlike BehaviorSubject, ReplaySubject can be created without an initial value.


7. When should ReplaySubject be used?

Answer

Use ReplaySubject when new subscribers need recent history, such as notifications, chat messages, logs, or event streams.


8. Can ReplaySubject multicast values?

Answer

Yes. ReplaySubject multicasts values to all active subscribers while replaying buffered values to new subscribers.


9. What are common enterprise use cases?

Answer

  • Chat history
  • Notification history
  • Audit logs
  • Transaction history
  • Stock price streams
  • WebSocket events

10. What are ReplaySubject best practices?

Answer

  • Use small buffer sizes.
  • Keep ReplaySubjects private.
  • Expose asObservable().
  • Avoid replaying sensitive information.
  • Prefer BehaviorSubject for current state.
  • Monitor memory usage.

Interview Cheat Sheet

Topic Remember
Initial Value Not Required
Replay Values Yes
Buffer Size Configurable
Time Window Supported
Multicasting Yes
Best Use Event History
Shared State Prefer BehaviorSubject
Encapsulation asObservable()
Memory Limit Buffer Size
Best Practice Replay only what is necessary

Summary

ReplaySubject extends the capabilities of RxJS Subjects by storing and replaying previous values to new subscribers. It is particularly useful when late subscribers need recent history, such as notifications, chat messages, transaction events, or real-time market data. By carefully selecting buffer sizes and time windows, ReplaySubject enables efficient event replay while maintaining good performance and scalability in enterprise Angular applications.


Key Takeaways

  • ✔ ReplaySubject stores multiple previous values.
  • ✔ New subscribers receive buffered history immediately.
  • ✔ Buffer size determines how many values are replayed.
  • ✔ Time windows automatically expire old events.
  • ✔ ReplaySubject supports multicasting.
  • ✔ Keep ReplaySubjects private.
  • ✔ Expose only asObservable().
  • ✔ Avoid large or unlimited buffers.
  • ✔ Do not replay sensitive data.
  • ✔ ReplaySubject is an important Angular and RxJS interview topic.

Next Article

➡️ 75-AsyncSubject-QA.md