BACK
Use casesCache — shareReplay for shared responses
Use cases · 06

Cache — shareReplay for shared responses

Pattern

If ten components subscribe to "getCurrentUser()", without a cache you'll get ten HTTP requests. shareReplay(1) turns a cold Observable hot: the first subscriber triggers the request, the rest get the stored response.

When to use it

  • Reference data that doesn't change within a session.
  • Configs, the user profile, feature flags.
  • Careful with dynamic data — the cache has to be invalidated.

What we achieve

One request for N subscribers, and an instant response for those who subscribe later.

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