Lessons54. Project: cache a request with shareReplay
Lessons · 54
54. Project: cache a request with shareReplay
Project 6 — a cache in an Angular service
A typical Angular situation: a UserService exposes profile$. The navbar, the user menu, and the settings page all subscribe to it. Without a cache — three HTTP requests for the same profile.
A one-line fix
profile$ = this.http.get('/api/profile').pipe(
shareReplay({ bufferSize: 1, refCount: false })
);
What the options mean
bufferSize: 1— keep one latest result.refCount: false— the cache isn't dropped even when everyone unsubscribes. Good for long-lived services.
Your task
- In
createCachedProfile$, insidepipe, addshareReplay({ bufferSize: 1, refCount: false }). - The test confirms the
requestscounter equals 1 despite two subscribers (the second arrives after 80ms — already past the request's completion).
Deterministic check
This task's check runs in TestScheduler virtual time. If your solution is right, the console shows only Test Passed!. Don't add extra console.logs, or the check will fail.
Solution spoiler · click to reveal
const { defer, shareReplay } = Rx;
function createCachedProfile$(request$) {
return request$.pipe(
shareReplay({ bufferSize: 1, refCount: false })
);
} script.ts
CONSOLE · Console output
Hit Run to see the result...