Member-only story
The Best New Way To Cache API Responses with Angular & RxJs

Hey folks! Welcome 👋
This article is a rather special one!
Over the years, I’ve repeatedly got caught up in trying to implement this use case in a clean way. Often involving many colleagues, spending a bit too much time, but always without proper success.
Even though we could always come up with a working solution , the solution we got felt down right dirty…
Until now…
Today we’re going change that and learn about the best new way to implement time based caching for the API responses (or any other) RxJs streams in our Angular applications!
☕ This article is pretty focused on a single topic so you should be able to get through it in one go, still TLDR; can’t hurt nobody 😉
TLDR
- Original example use case of retrieving and caching the
apiKey
- Previous approaches how to solve it (before RxJs 7.1) and their flaws
- New better solution with the help from improved
share
operator made available in RxJs 7.1+ - Refactoring our original implementation
- Caveats, gotchas and comparing possible solutions and their trade-offs
- Working solution (StackBlitz) & Cheat Sheet
The Original Use Case
Let’s imagine an Angular application where in order to retrieve some data from a API endpoint (aka backend) we have to provide two HTTP headers:
- Standard
access-token
, eg JWT token which we retrieve when we sign in - Custom
api-key
which we have to retrieve from its dedicated endpoint (and we can because we already have theaccess-token
which is sufficient…)
Besides that, the
api-key
has time restricted validity which is not really predictable, please don’t ask me why… Let’s just say it will always be valid for at least 10 seconds after it was retrieved, potentially all the way up to one month 😅😅
Let’s explore what are our options to solve this use case…