The Dark Side Of shareReplay in RxJS.
What You Might Have Overlooked About shareReplay in RxJS
The shareReplay operator of RxJS is one of the most frequently used operators. It simply provides a copy for all subsequent subscribers so that the previous, usually complex, operation does not have to be performed again.
This is the case in Angular, for example, when several async pipes in the template are applied to the same observable, e.g. an HTTP request.
But what is the problem with this? Well, a normal HTTP request will generally not be a problem, as this is usually completed and therefore all subscriptions are terminated. However, I noticed that the shareReplay subscription is not terminated by default if all subscribers have completed their subscription. In my case, I had set up a periodic HTTP request via a timer and this survived the destruction of the associated component.
The Official Documentation of shareReplay has the right answer to the problem.
By default
shareReplay
will userefCount
of false, meaning that it will not unsubscribe the source when the reference counter drops to zero, i.e. the innerReplaySubject
will not be unsubscribed (and potentially run for ever)...
So it is important to define shareReplay as follows shareReplay({ bufferSize: 1, refCount: true })
.
I have created a small project at Stackblitz with which I can reproduce the problem. I hope my article has helped you and you have learned something for your daily work.