Cached

interface Cached<T>

A lazily-computed, invalidatable single value, i.e. a memoized version of a () -> T generator.

Unlike Kotlin's stdlib lazy { ... } delegate, a Cached value can be explicitly invalidated and later regenerated on demand, which makes it suitable for values that are expensive to compute but occasionally need to be recomputed (e.g. because some external state they depend on has changed). Use Cached.of to wrap a generator function:

val cached: Cached<T> = Cached.of { computeExpensiveValue() }
cached.value // computes and caches the value on first access
cached.invalidate() // forces the next access to recompute the value

Type Parameters

T

is the type of the cached value

Inheritors

Types

Link copied to clipboard
object Companion

Properties

Link copied to clipboard
abstract val isInvalid: Boolean

Whether value needs to be (re)computed, by invoking generator again, upon the next access. Always the logical negation of isValid.

Link copied to clipboard
abstract val isValid: Boolean

Whether value currently holds an up-to-date, already-computed result (i.e. generator does not need to be invoked again upon the next access).

Link copied to clipboard
abstract val value: T

Retrieves the cached value, computing it first (via the generator passed to Cached.of) if it is currently isInvalid.

Functions

Link copied to clipboard
open fun <R> ifValid(consumer: (T) -> R): Optional<out R>

Applies consumer to the cached value and returns the result wrapped in Optional.Some, but only if the value is currently isValid; otherwise, returns Optional.None without forcing a (re)computation.

Link copied to clipboard
abstract fun invalidate()

Marks the cached value as isInvalid, so that it is recomputed upon the next access to value.

Link copied to clipboard
abstract fun regenerate()

Ensures value holds an up-to-date result, computing it via the generator passed to Cached.of if it is currently isInvalid. Does nothing if the value is already isValid.

Link copied to clipboard
open fun <R> regenerating(consumer: (T) -> R): R

Ensures the cached value is up-to-date (see regenerate), then applies consumer to it, returning the result of consumer.