Question presented to candidate:
"Our header, sidebar and profile panel all show the current user, and the network tab shows GET /api/me three times on every page load. Explain why, and how shareReplay fixes it. What does refCount change?"
What a strong answer should cover:
HttpClientObservables are cold: everysubscribe()(including eachasyncpipe) sends a new request.shareReplay(n)multicasts: it subscribes to the source once, forwards values to all subscribers through an internal ReplaySubject, and replays the lastnvalues to subscribers who arrive later.share()alone dedupes concurrent subscribers but not late ones;shareReplayalso covers the late ones.refCount: withrefCount: false(theshareReplay(1)default) the source subscription stays alive even when every subscriber leaves; withrefCount: trueit is torn down at zero subscribers. For HTTP this matters mostly for in-flight requests; for never-completing sources it is the difference between a leak and none.- Errors are not cached: a failed request is retried by the next subscriber. Also: where to keep the shared Observable (a root service field, not a method that returns a new pipe each call), and cache invalidation.
Clarifying questions expected:
- "Should the cached value live for the whole session, or be refreshed (on navigation, after a time, after a mutation)?"
- "Is the source a one-shot HTTP call or a long-lived stream?"
Code / implementation expected: Yes β a request counter with and without shareReplay, ideally showing a late subscriber.