io.provenance.caching.Caching.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pb-grpc-client-common-kotlin Show documentation
Show all versions of pb-grpc-client-common-kotlin Show documentation
A GRPC client for communicating with the Provenance Blockchain
The newest version!
package io.provenance.caching
import java.time.OffsetDateTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.time.Duration
fun cached(ttl: Duration, block: () -> T): Cached {
return object : BaseCachedAsync(ttl) {
override fun fetch(): T = block()
}
}
interface Cached {
fun fetch(): T
fun get(): T
}
abstract class BaseCachedAsync(private val ttl: Duration) : Cached {
private val lastFetch = AtomicReference(OffsetDateTime.MIN)
private val cachedValue = AtomicReference()
override fun get(): T {
if (OffsetDateTime.now().isAfter(lastFetch.get().plus(ttl.inWholeMilliseconds, ChronoUnit.MILLIS))) {
cachedValue.set(fetch())
lastFetch.set(OffsetDateTime.now())
}
return cachedValue.get()
}
}