Need help with layercache?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

appmattus
161 Stars 15 Forks Apache License 2.0 90 Commits 0 Opened issues

Description

Caching made simple for Android and Java.

Services available

!
?

Need anything else?

Contributors list

layercache

CI codecov

Caching made simple for Android and Kotlin.

An important component of building offline-first architectures is to implement caching.

An offline-first architecture initially tries to fetch data from local storage and, failing that, requests the data from the network. After being retrieved from the network, the data is cached locally for future retrieval. This helps to ensure that network requests for the same piece of data only occur once—with subsequent requests satisfied locally.

At its simplest, a cache is nothing more than a key-value store with a getter and setter.

interface Cache {
    suspend fun get(key: Key): Value?
    suspend fun set(key: Key, value: Value)
}

The real power comes when we are able to compose two caches into a new cache. A memory cache should have a single responsibility to store data in memory, and a disk cache a single responsibility to store data on disk.

val cache = memoryCache.compose(diskCache)

For more details read Caching made simple on Android or watch the talk from droidcon London 2017.

Getting started

Base module

implementation("com.appmattus.layercache:layercache:")

Composing two caches

When

get
is called on the composed cache, the first cache will be checked and if available returned. If not the second cache will be checked and if available set in the first cache and returned.
composedCache: Cache = firstCache.compose(secondCache)

Transforming values

Transform values between data types. This can be used for serialisation and encryption amongst other things. i.e.

Cache → Cache

For two way transformations:

val cache: Cache = ...
val valueTransform: Cache = cache.valueTransform(transform, inverseTransform)

// or

val cache: Cache = ... val valueTransform: Cache = cache.valueTransform(TwoWayTransform)

One way transforms return a Fetcher instead of Cache, but otherwise work in the same way. A Fetcher simply implements no-op for

set
and
evict
.
val fetcher: Fetcher = ...
val valueTransform: Cache = cache.valueTransform(transform)

// or

val fetcher: Fetcher = ... val valueTransform: Cache = cache.valueTransform(OneWayTransform)

Encrypting values
implementation("com.appmattus.layercache:layercache-android-encryption:")

There is support for encrypting string keys and string values (in any cache) on Android with the

layercache-android-encryption
module. The library is using Google Tink to perform the encryption using AES-256 SIV for keys and AES-256 GCM for values.
// Encrypt key and value when both are strings
val cache: Cache = ...
val encryptedCache = cache.encrypt(context)

// Both key and value stored encrypted in cache encryptedCache.set("hello", "world")

// Encrypt values only when just the value is a string val cache: Cache = ... val encryptedCache = cache.encryptValues(context)

// Just value stored encrypted in cache encryptedCache.set("hello", "world")

Transforming keys

Transform keys to a different data type. i.e.

Cache → Cache
val cache: Cache = ...
val keyTransform: Cache = cache.keyTransform(transform)

// or

val cache: Cache = ... val keyTransform: Cache = cache.keyTransform(OneWayTransform)

Re-using in flight requests

If a get request is already in flight then this ensures the original request is returned. This may be necessary for disk and network requests along with transformations that take time to execute.

val newCache: Cache = cache.reuseInflight()

Serializer module

implementation("com.appmattus.layercache:layercache-serializer:")

Configures a transformation from JSON to a serialisable data class and vice-versa. This is useful to store data on disk or in a database. i.e.

Cache → Cache
@Serialize
data class Value(val value)

val cache: Cache = ...

val objectCache: Cache = cache.jsonSerializer(Value::class.serializer())

Android base module

implementation("com.appmattus.layercache:layercache-android:")

LruCache

val memoryCache: Cache = Cache.createLruCache(maxSize: Int)

// or

val memoryCache: Cache = Cache.fromLruCache(...)

DiskLruCache

val diskCache: Cache = Cache.createDiskLruCache(directory: File, maxSize: Long)

// or

val diskCache: Cache = Cache.fromDiskLruCache(...)

SharedPreferences

Create a cache backed by shared preferences.

val sharedPreferences = context.getSharedPreferences("filename", Context.MODE_PRIVATE)

val anyValueCache: Cache = sharedPreferences.asCache()

val stringValueCache: Cache = sharedPreferences.asStringCache()

val stringSetValueCache: Cache> = sharedPreferences.asStringSetCache()

val intValueCache: Cache = sharedPreferences.asIntCache()

val floatValueCache: Cache = sharedPreferences.asFloatCache()

val booleanValueCache: Cache = sharedPreferences.asBooleanCache()

val longValueCache: Cache = sharedPreferences.asLongCache()

EncryptedSharedPreferences
implementation("androidx.security:security-crypto:")

Use Jetpack Security to provide a cache backed by encrypted shared preferences where keys and values are both encrypted.

val masterKey = MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()

val sharedPreferences = EncryptedSharedPreferences.create( context, "filename", masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM )

val anyValueCache: Cache = sharedPreferences.asCache()

val stringValueCache: Cache = sharedPreferences.asStringCache()

val stringSetValueCache: Cache> = sharedPreferences.asStringSetCache()

val intValueCache: Cache = sharedPreferences.asIntCache()

val floatValueCache: Cache = sharedPreferences.asFloatCache()

val booleanValueCache: Cache = sharedPreferences.asBooleanCache()

val longValueCache: Cache = sharedPreferences.asLongCache()

Android LiveData module

implementation("com.appmattus.layercache:layercache-android-livedata:")

Given a cache we can convert it for use with LiveData. This makes the getter return a

LiveDataResult
which can be one of
Loading
,
Success
or
Failure
.
val liveDataCache = cache.toLiveData()

liveDataCache.get("key").observe(owner) { liveDataResult -> when (liveDataResult) { is LiveDataResult.Loading -> { // display in progress } is LiveDataResult.Success -> { // display liveDataResult.value } is LiveDataResult.Failure -> { // display liveDataResult.exception } } }

Download Maven Central

dependencies {
    implementation("com.appmattus.layercache:layercache:")

// To use with the Kotlin serializer
implementation("com.appmattus.layercache:layercache-serializer:<latest-version>")

// Provides support for ehcache
implementation("com.appmattus.layercache:layercache-ehcache:<latest-version>")

// Provides support for cache2k
implementation("com.appmattus.layercache:layercache-cache2k:<latest-version>")

// Provides LruCache &amp; DiskLruCache support for Android
implementation("com.appmattus.layercache:layercache-android:<latest-version>")

// Provides one-line String encryption for Android
implementation("com.appmattus.layercache:layercache-android-encryption:<latest-version>")

// Provides conversion from Cache into LiveData for Android
implementation("com.appmattus.layercache:layercache-android-livedata:<latest-version>")

}

Contributing

Please fork this repository and contribute back using pull requests.

All contributions, large or small, major features, bug fixes, additional language translations, unit/integration tests are welcomed.

License License

Copyright 2020 Appmattus Limited

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.