commonMain.contextual.ContextualMemoryCache.kt Maven / Gradle / Ivy
package opensavvy.cache.contextual
import kotlinx.coroutines.Job
import opensavvy.cache.MemoryCache
import opensavvy.cache.cachedInMemory
import opensavvy.state.coroutines.ProgressiveFlow
internal class ContextualMemoryCache(
upstream: ContextualCache,
job: Job,
) : ContextualCache {
private val cache = ContextualWrapper(upstream)
.cachedInMemory(job) as MemoryCache, F, V>
override fun get(id: I, context: C): ProgressiveFlow =
cache[id to context]
override suspend fun update(values: Collection>) =
cache.update(values.map { (id, context, value) -> id to context to value })
override suspend fun expire(ids: Collection) {
val filterIds = ids.toSet()
cache.expireIf { (id, _) -> id in filterIds }
}
override suspend fun expireContextual(ids: Collection>) =
cache.expire(ids)
override suspend fun expireAll() =
cache.expireAll()
}
/**
* In-memory [ContextualCache] layer.
*
* @see opensavvy.cache.cachedInMemory Non-contextual equivalent
*/
fun ContextualCache.cachedInMemory(job: Job): ContextualCache =
ContextualMemoryCache(this, job)