https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

jakub.dyszkiewicz

04/09/2019, 12:06 PM
Hello, I’m experimenting with Coroutines. Is there any abstraction to do something similar as
.sample(Duration)
? https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#sample-java.time.Duration- on channel. I’d like to throttle consumer of channel to process the latest data not often than every 1s
ok, I solved it in a different way 😉
Copy code
val limiter = TimeBasedRateLimiter(Duration.ofSeconds(5))
suspend fun updateSnapshot(combinedState: Pair<State, State>) = limiter {
    println("Updating snapshot")
    println(combinedState)
}

class TimeBasedRateLimiter(val limit: Duration) {
    private var lastInvocation: Long = 0

    suspend operator fun invoke(fn: suspend () -> Unit) {
        if ((System.currentTimeMillis() - lastInvocation) > limit.toMillis()) {
            fn()
            lastInvocation = System.currentTimeMillis()
        }
    }
}
2 Views