Overview
If your mobile app requires frequent trips to the server, this article is for you. We will discuss creating a class that you can use to transparently make your app faster by selectively caching items in memory. And thus, making your users very happy. This class can even apply individual refresh times to each cached item. Schweet!
One additional thing. Our class will allow us to update the cache without a separate trip to the server. This means that we can add/modify/delete an item from the cached list and obtain a freshly ordered list from the cache. Note: The need for this is apparent when a new item is submitted to the server, and a refresh of the list is required. The same goes for an item that is modified or deleted. Schweeter!
Data Caching – A Quick Review
So why do we want or need to cache data? One answer. We want to improve the performance of our applications. Since modern day applications are distributed, data can come from a number of different sources; some close by, and some continents apart. However, our applications are responsible for bringing together information and presenting it to the user in a timely manner regardless of all of the data sources involved.
Now let’s define caching. The definition of caching is to improve performance by transparently storing data such that future requests for that data can be served faster.
Let’s Get Started
Let’s look at a quick example usage. Here we have a list of serialized products being cached, and we will now retrieve this list.
String serializedProducts = (String)AppCache.getInstance().getValue(productsKey);
if (serializedProducts == null) {
// load fresh data
serializedProducts = productRepository.load(productsKey);
// add new data string into cache
AppCache.getInstance().addValue(productsKey, serializedProducts, refreshDateTime);
}
// now deserialize "serializedProducts" to obtain a list of Product entities
We are simply asking our cache to return data for our requested key. Data is returned if two criterion are met as follows:
- the item is in cache
- the item is still fresh (i.e., does NOT require refreshing)
If we receive the item, we can assume the item is fresh. If null is returned, we need to get a fresh copy of our item, as shown in line 2, when (serializedProducts == null).
Once we have obtained the item, we need to deserialize it to obtain our list of Product entities. More information on serialization/deserialization can be found here.
More coming soon!
