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…
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 😉
- Original example use case of retrieving and caching the
- Previous approaches how to solve it (before RxJs 7.1) and their flaws
- New better solution with the help from improved
shareoperator 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:
access-token, eg JWT token which we retrieve when we sign in
api-keywhich we have to retrieve from its dedicated endpoint (and we can because we already have the
access-tokenwhich is sufficient…)
Besides that, the
api-keyhas 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…