Prioritizing fresh data with RxJS network-first strategy
In this recipe, we’re going to follow the opposite approach to the preceding recipe. Here, we’re going to send a network request first, and if we are offline and the request fails, then we’ll fall back to the cache. In this way, we can always have the latest fresh values in our cache, even when we go offline.
How to do it…
We are going to leverage Angular’s interceptors and simulate the same behavior as if we were implementing a network-first offline strategy inside a service worker.
Step 1 – Sending a network request when online
When we have our interceptor ready, we can intercept each HTTP request, update the cache storage to keep the data fresh in the cache, and continue with the request:
const openCache$ = from(caches.open('my-app-cache'));
const continueRequest$ = next(req);
return continueRequest$.pipe(
withLatestFrom(openCache$),
map(([response...