# suparnatural-cache
# Introduction
A super fast, persistable, thread safe in-memory cache for iOS and Android.
Check the API documentation for details.
# Setup
- Add the repository to your project.
repositories { mavenCentral() }
1
2
3 - Add
implementation 'com.suparnatural.kotlin:cache:version'
tocommonMain
.
With the hierarchical project structure, you generally need to add the dependency to
commonMain
only. Other targets are also available in case you need to override this behavior.
# Concepts
# Models
Every object which you want to cache must implement Cacheable
interface. The only requirement is to implement cacheKey()
to return a unique identifier using which the object will be identified.
class Person(val name: String): Cacheable {
fun cacheKey() = name
// this method is only required if you want your objects to be serializable.
fun serializeForPersistence() = ""
}
2
3
4
5
6
# CacheManager
CacheManager is a thread safe singleton which you will interact with. It needs to be initialized by calling initialize which accepts an instance of Cache
. The library provides a default implementation with an abstract class
InMemoryCache
with a FIFO cache replacement policy. On top of that, you can choose a hashing algorithm as well. Two such algorithms are provided Linear Probing
and Robinhood Hashing
.
# Usage
# Initialize Without persistent storage.
CacheManager.initialize(LinearProbingCache(cacheSize, persistentStores = emptyList()))
CacheManager.cache.addObject(Person("BOB"))
2
# Initialize With persistent storage
class Person {
fun serializeForPersistence() = "$name"
}
val diskStorage = DiskStore(blocking = true) // this can be non blocking too. Check the API docs
CacheManager.initialize(LinearProbingCache(cacheSize, persistentStores = listOf(diskStorage)))
CacheManager.cache.addObject(Person("BOB"))
// Person('BOB') will be be persisted to a file called "BOB" with contents = "BOB"
2
3
4
5
6
7
8
# Custom Store
A custom store can also be used to back the in memory cache.
Implement the CacheStore
interface and pass it in persistentStores
argument.
# Rehydration
If you are using a persistent store, chances are that you want your cache to be reloaded after your app's cold start. If that is the case, then you must provide a list of preprocessors to the storage object where each item in the list is a CacheStorePreprocessor
.
# Custom Cache Replacement Policy
By default, the inmemory cache uses a FIFO replacement policy where the old object in the cache is evicted first when cache is full. You can also create your own replacement policy like LRU
by implementing CacheReplacementPolicy
and then passing it in the Linear Probing
or Robinhood Hashing
constructors.
# API Docs
Check out the API Docs. They are always up to date with code examples.