ReactiveCircus / cache4k

In-memory Cache for Kotlin Multiplatform.
https://reactivecircus.github.io/cache4k/
Apache License 2.0
272 stars 20 forks source link

Dynamic TTL #18

Open caeus opened 2 years ago

caeus commented 2 years ago

Is it possible to set the expiration time during execution of the loader?

Trying to cache some oauth tokens whose expiration time is known when the loader gets them. Not before.

glockbender commented 2 years ago

It is such a good and useful enhancement and it would be awesome to have it in this lib.

Shabinder commented 1 year ago

we even have kotlinx.datetime which should make this simpler to impl for all platforms in commonMain only.

ychescale9 commented 1 year ago

Thanks everyone, I might take a look at this soon.

Can you share a few examples of your use cases and how you think the APIs should look like? Is this a feature you've used in other caching libraries in the past?

glockbender commented 1 year ago

Example of function description:


public data class LoaderContext internal constructor(
    var expireAfterAccessDuration: Duration,
    var expireAfterWriteDuration: Duration
)

public suspend fun get(key: Key, loader: suspend LoaderContext.() -> Value): Value
// looks like it should be a new 'put' function with 'customizing'
public suspend fun put(key: Key, loader: suspend LoaderContext.() -> Value)

Example of usage:

suspend fun cacheToken(key: String, ttl: Duration): Any {
   cache.put(key) {
      // by default cache-level configured values are set
      this.expireAfterAccessDuration = ttl
      // ...
   }
}

suspend fun someFun(key: String, ttl: Duration): Any {
   cache.get(key) {
      this.expireAfterWriteDuration = ttl
      // ...
   }
}

Is this a feature you've used in other caching libraries in the past?

Using it a lot with Redis

caeus commented 8 months ago

I'd add the feature as part of the builder:

dynamicExpireAfterWrite{ it.expires_in.seconds }