shareReplay with takeUntil: need explicit buffer reset on destruction signal
0 reputation · 12 Jan 2021, 15:56 UTC
0 reputation · 12 Jan 2021, 15:56 UTC
Goal: ensure that when migrating a small RxJS‑based application version‑by‑version without downtime, any cached values from a shareReplay stream are cleared as soon as the destruction signal for the old version emits.
Constraint: the takeUntil operator completes the source observable, but shareReplay retains its replay buffer until the internal refCount drops to zero, which may keep the old version’s source subscribed longer than desired.
Uncertainty: whether it is sufficient to rely on the refCount behavior to discard the buffer, or whether a public reset() method on the shared replay subject should be exposed to forcefully flush replayed values.
Questions: Should we implement a reset() method to manually clear the replay buffer on destruction? Can we safely depend on refCount reaching zero after takeUntil to avoid stale data? What are the trade‑offs between manual reset and refCount‑based cleanup regarding migration safety and memory usage?
32275 reputation · 13 Jan 2021, 03:50 UTC
If you can guarantee that no component or service keeps a subscription to the shareReplay after the destruction signal, you do not need a manual reset; the refCount will drop to zero when takeUntil completes the source and the internal Subject will be unsubscribed, clearing the buffer.
If any lingering subscription might remain (e.g., a long‑lived service that never unsubscribes), you should expose a reset method to forcibly clear the replay buffer.
function shareReplayWithReset(bufferSize, windowTime) {
let subject;
const shared = shareReplay(bufferSize, windowTime).pipe(
multicast(() => {
subject = new ReplaySubject(bufferSize, windowTime);
return subject;
}),
refCount()
);
return {
observable: shared,
reset: () => { if (subject) subject = new ReplaySubject(bufferSize, windowTime); }
};
}
Call reset() immediately after the destruction signal emits.
Do any long‑lived parts of the application retain a subscription to the shareReplay after the destruction signal? If yes, you need the reset approach; if not, you can safely depend on refCount reaching zero.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.