Shripad Avhad
Shripad Avhad

Reputation: 21

How can we get OLD data each time we subscribe observable in angular?

Recently I come to this requirement where I subscribing observable 3 times in 3 different for loop.

I am getting updated data each time. How can we get OLD data each time we subscribe observable in angular?

Upvotes: 1

Views: 1966

Answers (3)

Santi Barbat
Santi Barbat

Reputation: 2295

You can use a ReplaySubject that "Replays" or emits old values to new subscribers:

A variant of Subject that "replays" or emits old values to new subscribers. It buffers a set number of values and will emit those values immediately to any new subscribers in addition to emitting new values to existing subscribers.

import * as Rx from "rxjs";

const subject = new Rx.ReplaySubject(2);

// subscriber 1
subject.subscribe((data) => {
    console.log('Subscriber A:', data);
});

subject.next(Math.random())
subject.next(Math.random())
subject.next(Math.random())

// subscriber 2
subject.subscribe((data) => {
    console.log('Subscriber B:', data);
});

subject.next(Math.random());

// Subscriber A: 0.3541746356538569
// Subscriber A: 0.12137498878080955
// Subscriber A: 0.531935186034298
// Subscriber B: 0.12137498878080955
// Subscriber B: 0.531935186034298
// Subscriber A: 0.6664809293975393
// Subscriber B: 0.6664809293975393

Code source: Understanding rxjs BehaviorSubject, ReplaySubject and AsyncSubject

Upvotes: 2

TwitchBronBron
TwitchBronBron

Reputation: 3186

You will need to keep track of the old values yourself, as Angular doesn't provide a way to get at those old values. Here's some sample code showing one way of doing this.

@Component(...)
export class SomeComponent {
    constructor(private dataService){   }

    private oldData;

    ngOnInit(){
       this.dataService.getSomeData().subscribe((data)=>{
          if(this.oldData){
             //do stuff with old data. 
             //Not available until the SECOND time this callback is called
          }
          this.oldData = data;

          //do stuff with new data
       });
    }
}

Upvotes: 0

Durgesh
Durgesh

Reputation: 205

You can use service property or component property for this. If you want to keep your data local to component then go with one property and keep pushing the received data in that property in next callback. On the other hand if you want to share data/logic with another component then go with service with same approach of pushing data and just inject service into another component where you want to use it.(don't forget to use same instance of service)
Services

Upvotes: 0

Related Questions