Optimizing data freshness and performance with the Stale-While-Revalidate strategy
Stale-While-Revalidate is a common strategy when we want to always show some data to the user, even if the data might be out of date. After that, we send the network request in the background and refresh the data afterward. This can also help us if we go offline since we can show the old data first, then retry and check in the background if we are back online.
How to do it…
We are going to leverage Angular’s interceptors and simulate the same behavior as if we were implementing the Stale-While-Revalidate offline strategy inside a service worker. The strategy here is to create two streams that will emit values in order, first for the cache data, and the second for the network response data.
Step 1 – Extracting data from the cache
Now that our interceptor is ready, we can intercept each HTTP request, and show cached data while we are offline:
const openCache$ ...