I need to share a hot Observable
between multiple subscribers and emit the latest value to new subscribers. I am trying to achieve this with shareReplay(1)
, however, the first subscriber fails to retrieve the latest value because the shareReplay
operator doesn’t do anything when there is no subscription, so it doesn’t store anything for the first subscriber.
How do I fix this without having a permanent subscription just to keep shareReplay
alive?
Advertisement
Answer
You can solve your problem using publishReplay(1)
instead of shareReplay(1)
:
const subject = new Subject() const source$ = subject.pipe(publishReplay(1)) source$.connect(); subject.next(1) subject.next(2) subject.next(3) source$.subscribe(v => console.log(v)) subject.next(4) subject.next(5) subject.next(6)
Output:
3 4 5 6
The important part is that with publishReplay
, you can control when the subscription starts (source$.connect()
). shareReplay
will start only with the first subscription.