cachedInBrowserStorage

fun <Identifier, Failure, Value : Any> Cache<Identifier, Failure, Value>.cachedInBrowserStorage(storage: Storage, keyPrefix: String, serializeIdentifier: (Identifier) -> String?, serializeValue: (Value) -> String?, deserializeValue: (String) -> Value?): Cache<Identifier, Failure, Value>(source)

In-browser Cache layer.

General behavior

Updates from the previous cache are stored in the storage engine. When get is called, results are returned from the storage engine if available. Otherwise, the request is transmitted to the previous layer.

Elements are deleted when the storage engine when expire is called. To reduce the size of the cache automatically, add a subsequent layer for it (e.g. expireAfter).

Observability

Currently, the implementation is based on polling. If the value changes in the cache, all cache instances notice after a few seconds. This can be used to share values between tabs: if a cache instance in a tab gets a result, other instances in other tabs will notice them and avoid starting new requests.

However, the current implementation only stores values when they are successful, so if two tabs start the same request at the same time, they won't be deduplicated (both requests will go through). Failed values are not stored either.

Example

fun serializeKey(id: Int) = id.toString()
fun serializeValue(value: Double) = value.toString()
fun deserializeValue(value: String) = value.toDouble()

val squareRoot = cache<Int, Double> { sqrt(it) }
.cachedInBrowserStorage(window.localStorage, "sqrt", serializeKey, serializeValue, deserializeValue)
.cachedInMemory(…)
.expireAfter(…)

Parameters

storage

The browser storage engine to use.

keyPrefix

A short string that is appended before the identifier. The prefix is important to avoid naming conflicts with other values that may be stored in the storage engine.

serializeIdentifier

A function that converts an identifier to a String. If the function returns null, this layer assumes the value cannot be stored and no-ops.

serializeValue

A function that converts a cached value to a String. If the function returns null, this layer assumes the value cannot be stored and no-ops.

deserializeValue

A function that converts a string generated by serializeValue into its original value. If the function returns null, this layer assumes the value cannot be stored and no-ops.