Lessons42. shareReplay: a shared source plus a cache
Lessons · 42
42. shareReplay: a shared source plus a cache
shareReplay — multicast + cache
shareReplay is share with extra memory. It not only makes the source shared, it also remembers the last N values. A late subscriber instantly gets the cached values without re-running the source.
http.get(...).pipe(shareReplay(1))
// first subscription → one HTTP request → the response is cached
// second subscription (even an hour later) → gets the cache instantly
Configuration
The modern form is shareReplay({ bufferSize, refCount }):
bufferSize: 1— how many recent values to keep.refCount: true— shut the source down when there are no subscribers.refCount: false— the source is held "forever" (or until garbage-collected). Good for global caches.
Careful with a forever-cache
A cached value never refreshes on its own. If the data can change, you need an invalidation strategy (a new source, a key, an expiration).
Your task
- In
request$.pipe(...), addshareReplay({ bufferSize: 1, refCount: false }). - The test checks: the
requestscounter equals 1, and both subscribers got the data.
Deterministic check
This task is verified in virtual time via TestScheduler. If the solution is correct, the console shows only Test Passed!. Don't add extra console.log calls, or the check will fail.
Solution spoiler · click to reveal
const { Observable, shareReplay } = Rx;
let requests = 0;
const request$ = new Observable(subscriber => {
requests += 1;
const subscription = cold('20ms a|', { a: 'Data' }).subscribe(subscriber);
return () => subscription.unsubscribe();
});
const cached$ = request$.pipe(
shareReplay({ bufferSize: 1, refCount: false })
); script.ts
CONSOLE · Console output
Hit Run to see the result...