package net.sergecyh.diwan.tools import kotlin.time.Clock import kotlin.time.Duration import kotlin.time.Instant /** * Experimental. * * limit invocations rate of [invoke] to once per [minimalInterval] or less frequent. * Note that it is not a debouncing, it just ignores too frequent calls! */ @Suppress("unused") class RateLimiter(val minimalInterval: Duration) { var lastExecutedAt = Instant.DISTANT_PAST private set /** * invoke [f] if the last invocation was earlier than now minus [minimalInterval], otherwise * do nothing. * @return the value returned by [f] if it was actually invoked this time, null otherwise */ suspend operator fun invoke(f: suspend () -> T): T? = if (Clock.System.now() - lastExecutedAt > minimalInterval) { f().also { lastExecutedAt = Clock.System.now() } } else null }