Member-only story
RxJS: What’s Changed with shareReplay?
In RxJS version 6.4.0, a change was made to the shareReplay
operator. Let’s look at why the operator needed to be changed, what was changed and how the change can be used to avoid surprises — and bugs.
If you’re only interested in the change, skip to the TL;DR at the bottom of the article.
The operator’s history
The shareReplay
operator was introduced in version 5.4.0.
Like the share
operator, shareReplay
returns a hot, reference-counted observable, but replays the specified number of next
notifications. Also, if the source completes, it ensures that the complete
notification is replayed to new subscribers and that no further subscriptions are made to the source observable.
In the version 5.4.0 implementation of shareReplay
, when the subscriber reference count dropped to zero — without the source having completed — the operator would unsubscribe from the source. Subsequent resubscription to the shared observable would increment the reference count from zero to one, effecting a resubscription to the source using a newly-created ReplaySubject
.
Let’s look at an example: