# What is a ReplaySubject in Angular ?

In 
Published 2022-12-03

This tutorial explains to you what a ReplaySubject is in Angular and also provide you with an example.

In Angular, in many cases we need to see the value(s) of a stream in real time and in the same time we need to get access to this stream to many consumers (subscribers). Each subscriber/ consumer will do different things function on the stream value(s). In this situation we have to define a Subject, a BehaviorSubject, a ReplaySubject or a AsyncSubject.

A ReplaySubject = a set/ stream of data a subscriber (consumer) can subscribe to. The subscriber can see the NEW data in the stream and also the PAST values in the stream. It might be useful for you to take a look at the following articles as well: Subject in Angular and BehaviorSubject and AsyncSubject in Angular.

In order to use this feature, you have to import "ReplaySubject" from 'rxjs' or 'rxjs/ReplaySubject' into the component that use it:

import { ReplaySubject } from 'rxjs';

Here is the code we used for showing ReplaySubject behavior in Angular 4:

/* app.component.ts */
import { Component } from '@angular/core';
import { ReplaySubject} from 'rxjs';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
 
  products = [
    {name:"apples", price:10, onStock:"Y"},
    {name:"bananas", price:5, onStock:"Y"},
    {name:"tomatoes", price:11, onStock:"Y"}
  ];
 
  ngOnInit() {
     
    console.log('ReplaySubject:');
    let subject4 = new ReplaySubject<number>();
    subject4.next(1);
    subject4.next(2);
 
    let subscription41 = subject4.subscribe( var1  => {
      console.log('subscription41 /'+var1+'/');
    });
    console.log('-----------------------------------');
    subject4.next(3);
 
    console.log('===================================');
  }
}

And here is the result in the browser console: