blob: 66fba8d0db5c68fe4e68bd3aef690a4038894edc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
package moe.nea.ledger
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
import kotlin.time.Duration.Companion.seconds
class DebouncedValue<T>(private val value: T) {
companion object {
fun <T> farFuture(): DebouncedValue<T> {
val value = DebouncedValue(Unit)
value.take()
@Suppress("UNCHECKED_CAST")
return value as DebouncedValue<T>
}
}
val lastSeenAt = System.nanoTime()
val age get() = (System.nanoTime() - lastSeenAt).nanoseconds
var taken = false
private set
fun get(debounce: Duration): T? {
return if (!taken && age >= debounce) value
else null
}
fun replace(): T? {
return consume(0.seconds)
}
fun consume(debounce: Duration): T? {
return get(debounce)?.also { take() }
}
fun take() {
taken = true
}
}
|