Caching Objects Easily to Disk Using Reservoir

Reservoir is a library that makes object caching easier than ever. It allows us to serialize and cache any object to the part of internal storage that is dedicated to your app for caching purposes.

As always, the first thing to do is to add the dependency for Reservoir to module-level “build.gradle” file:

Then, you need to initialize the library inside your custom Application’s onCreate() method as follows:

Now, you are good to go. Reservoir caches objects in key-value pairs. So, you can easily put, get, or delete objects to/from cache synchronously or asynchronously. You can also check if an object exists in cache, or clear the entire cache in just one line of code. Let me show the couple of them in a code snippet:

You can find out all the capabilities of Reservoir here on its GitHub page:

What you need to be careful about this library is that you may not find an object previously cached. That might happen because you reach the limit of cache size that you set while initializing Reservoir. In such case, the library discards objects starting from least recently used ones since it depends on Disk LRU Cache library developed by Jake Wharton. Or, you may not find an object just because OS decides to delete it, for instance, due to the device running low on storage. So, you shouldn’t rely on the existence of your cached objects.

The last thing I want to emphasize about Reservoir is the cache size you set while initializing the library “should always have a reasonable maximum, such as 1 MB” as recommended here.

Leave a Reply

Your email address will not be published. Required fields are marked *