Udi Mazor
Udi Mazor

Reputation: 1826

shareReplay changes the order

I wrote some Observable from Array [1, 2, 3, 4, 5] which logs at each iteration. So the output I am getting is : 1,2,3,4,5 like the way it should be.

When I am adding shareReplay(2) I am getting the last two iteration - 4,5. It make no sense to me.. I was expecting to get 1,2 as an output.

numbers$: Observable<number> = from([1, 2, 3, 4, 5, 6, 7]);

ngOnInit() {
this.numbers$.pipe(
  shareReplay(2),
  refCount()
).subscribe(data => console.log(data));

}

I got it on stackBlitz: https://stackblitz.com/edit/hello-angular-6-yb387t?file=src/app/app.component.ts

Upvotes: 1

Views: 665

Answers (1)

D&#225;niel Barta
D&#225;niel Barta

Reputation: 1177

ShareReplay always replays the last two emitted value from the observable. If you need the first two, you should use take(2) instead. If you also need the replay functionality, you can still use shareReplay:

this.numbers$.pipe(
  take(2),
  shareReplay()
).subscribe(data => console.log(data));

One more thing: when you use shareReplay you don't need to use refCount as it is already used by shareReplay under the hood. There is a very good explanation for this here.

Upvotes: 2

Related Questions