2

I have an observable and I'm trying to make a replay subject from. It should emit the current and all previous events that the observable emitted.

Here is what I thought would work, as per this answer:

// create an observable from dummy array and a blank replay subject
const observable$ = from([1, 2, 3])
const replay$ = new ReplaySubject()

// create a replay subject from the observable (not working as expected)
observable$.subscribe(replay$)

// log out the events
observable$.subscribe(e => console.log('observable', e) )
replay$.subscribe(e => console.log('replay', e))

Logs

observable 1
observable 2
observable 3
replay 1
replay 2
replay 3

The behavior I'm looking for is such that the replay subject emits the previous events as well, like so:

replay [1]
replay [1, 2]
replay [1, 2, 3]

How can I archieve this?

Hoff
  • 38,776
  • 17
  • 74
  • 99

1 Answers1

1

ReplaySubject replays the whole sequence only on subscription. This means only when you call replay$.subscribe(). After that it only passes through all emissions.

From what output you want to get it looks like you want to chain it with scan() because ReplaySubject emits items one by one and not as accumulated arrays as you expect.

observable$.pipe(
  scan((acc, val) => [...acc, val], []),
).subscribe(replay$);

Live demo: https://stackblitz.com/edit/rxjs-yfgkvf?file=index.ts

martin
  • 93,354
  • 25
  • 191
  • 226