InMemoryCache

class InMemoryCache<V : Any>(maxSize: Int? = null, currentTimeMillis: () -> Long = System::currentTimeMillis) : TimestampedCache<V>

An in-memory TimestampedCache with optional LRU eviction.

Mirrors SwiftyNetwork's InMemoryCache. State is guarded by a Mutex (the Kotlin analog of the Swift actor), and storage uses an access-ordered LinkedHashMap so reads promote entries to most-recently-used. When maxSize is set, the least-recently-used entries are evicted once the limit is exceeded.

Mutations are published to changes so reactive consumers can observe the cache; reads (which only reorder for LRU) do not emit.

Parameters

maxSize

maximum number of entries to retain, or null for unbounded.

currentTimeMillis

time source, injectable for deterministic tests.

Constructors

Link copied to clipboard
constructor(maxSize: Int? = null, currentTimeMillis: () -> Long = System::currentTimeMillis)

Functions

Link copied to clipboard
open override fun changes(): Flow<CacheChange>

A hot stream of CacheChanges for this cache. The default is an empty flow, so caches that cannot observe mutations are simply non-reactive; observable caches override this.

Link copied to clipboard
suspend fun count(): Int

The current number of entries.

Link copied to clipboard
open suspend override fun entry(key: CacheKey): CacheEntry<V>?

Atomically returns the value and its timestamp for key, or null if absent.

Link copied to clipboard
open suspend override fun removeAll()

Removes every entry.

Link copied to clipboard
suspend fun removeExpiredEntries(maxAgeMillis: Long)

Removes entries older than maxAgeMillis relative to the current time.

Link copied to clipboard
open suspend override fun removeValue(key: CacheKey)

Removes any value stored for key.

Link copied to clipboard
open suspend override fun setValue(value: V, key: CacheKey)

Stores value for key, stamping it with the current time.

open suspend override fun setValue(value: V, key: CacheKey, timestamp: Long)

Stores value for key stamped with the given epoch-millisecond timestamp.

Link copied to clipboard
open suspend override fun timestamp(key: CacheKey): Long?

Returns the epoch-millisecond timestamp recorded for key, or null if absent.

Link copied to clipboard
open suspend override fun value(key: CacheKey): V?

Returns the value stored for key, or null if absent.