This post is about an experimental approach and I am sure there are other approaches for solving a similar problem. If so, please comment on this article.
Demo: https://ashwin-sureshkumar.github.io/angular-cache-service-blog/ Note: open the developer console to see log messages
Stackblitz Editor: https://stackblitz.com/edit/angular-simple-cache-service-with-rxjs
Cache is a simple data storage to store data so that it can be accessed faster the next time the same info is needed to improve performance and user experience. Here, the data can be a derived/calculated value or duplicate data/requests made from different sections of the application.
We are going to build a simple list of stories from Hackernews API to show the top stories from their homepage and implement infinite scroll to load more data.
To make things interesting, I want to show the Karma of the author for each post but Karma is not returned in the stories API call. It has to be fetched for each user with a separate API call. So as we load the list, we will pick the author and make an API call to populate the karma of the user. So if incase the same user is repeated in the list, we will end up making multiple calls without any kind of caching service.
Note: This is a made up scenario to demonstrate the usage of a cache service.
We will see cache service code, the demo of the implementation and then break the code into sections for a walk through.
In the above gif I am logging the API calls (purple), notifying the inflight observables (blue) and when the data is received from cache (green).
Demo: https://ashwin-sureshkumar.github.io/angular-cache-service-blog/ Note: open the dev console to log messages
We initialize three properties to our service,
Let’s look at
get method does few things,
do) method chain which calls the set method.
set method is pretty straight forward, set the given the data in cache and notifies all the subscribers with data.
notifyInFlightObservers check if key exists in inFlightObservables and if there are subscribers for the key.
It is very straight forward, I am calling the
id (key for the cache) and
fallback as the API call here and thats it.
This is a simple implementation of a caching service on the UI layer. Hope this brings in some thoughts and other implementation ideas.
If you liked this post, please share, comment and recommend.
Angular — Simple Infinite scroller directive with RxJS Observables: https://codeburst.io/angular-2-simple-infinite-scroller-directive-with-rxjs-observables-a989b12d4fb1
Naive Infinite scroll in Reactive Programming using RxJS Observables https://hackernoon.com/naive-infinite-scroll-in-reactive-programming-using-rxjs-observables-4a605d3146e8