commonMain.contextual.ContextualExpirationCache.kt Maven / Gradle / Ivy
package opensavvy.cache.contextual
import kotlinx.coroutines.CoroutineScope
import kotlinx.datetime.Clock
import opensavvy.cache.expireAfter
import opensavvy.state.coroutines.ProgressiveFlow
import kotlin.time.Duration
internal class ContextualExpirationCache(
private val upstream: ContextualCache,
duration: Duration,
clock: Clock,
scope: CoroutineScope,
) : ContextualCache {
private val cache = ContextualWrapper(upstream)
.expireAfter(duration, scope, clock)
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) {
// ExpirationCache doesn't store data, so we can directly expire the upstream
upstream.expire(ids)
}
override suspend fun expireContextual(ids: Collection>) {
// ExpirationCache doesn't store data, so we can directly expire the upstream
upstream.expireContextual(ids)
}
override suspend fun expireAll() {
// ExpirationCache doesn't store data, so we can directly expire the upstream
upstream.expireAll()
}
}
/**
* Age-based [ContextualCache] expiration strategy.
*
* @see opensavvy.cache.expireAfter Non-contextual equivalent
*/
fun ContextualCache.expireAfter(duration: Duration, scope: CoroutineScope, clock: Clock): ContextualCache =
ContextualExpirationCache(this, duration, clock, scope)
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated(message = "Specifying the clock explicitly will become mandatory in 2.0.")
fun ContextualCache.expireAfter(duration: Duration, scope: CoroutineScope): ContextualCache =
ContextualExpirationCache(this, duration, Clock.System, scope)