BACK
Use casesCache invalidation — refreshing a shareReplay cache
Use cases · 28

Cache invalidation — refreshing a shareReplay cache

Pattern

shareReplay caches the response for all subscribers — great, until the data changes. But after a mutation (a record created/deleted/updated) you need a way to force the cache to reload.

The problem it solves

Use plain shareReplay(1) and the response is frozen forever. You POST, the server data updates, but the UI shows the old value. Imperatively resetting service fields falls apart with multiple subscribers.

Operators and why they matter

  • Subject — the invalidation trigger. Call invalidate$.next() to rebuild the cache.
  • startWith — the initial load with no separate method. The first load happens on its own.
  • switchMap — on a new trigger, cancels the old request and starts a fresh one.
  • shareReplay({ bufferSize: 1, refCount: true }) — all subscribers get the same cached response. refCount is needed to shut the upstream down when there are no subscribers.

Gotchas

  • shareReplay(1) without the object config — refCount: false by default, and the upstream lives forever. That's a leak.
  • mergeMap instead of switchMap — two parallel refreshes; the old one can overwrite the new.
  • Don't forget to call invalidate$.next() after a successful mutation. Otherwise the UI shows stale data.

What you get

One refreshable cache for all subscribers. Every component sees the update in sync after invalidate.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...