Skip to content

Instantly share code, notes, and snippets.

@justasm
Last active August 22, 2018 12:23
Show Gist options
  • Save justasm/69a66dd95a5ffeee16ec8dbe988e6ab4 to your computer and use it in GitHub Desktop.
Save justasm/69a66dd95a5ffeee16ec8dbe988e6ab4 to your computer and use it in GitHub Desktop.
Debounced property delegate Android implementation
import android.os.Handler
fun <T> debounced(initialValue: T, debounceMs: Long = 500L): Debounced<T> {
return AndroidDebounced(initialValue, debounceMs)
}
private class AndroidDebounced<T>(initialValue: T, private val debounceMs: Long) : Debounced<T> {
private val handler = Handler()
private var _value: T = initialValue
override var value: T
get() = _value
set(value) {
handler.removeCallbacksAndMessages(null)
handler.postDelayed({ _value = value }, debounceMs)
}
}
@file:Suppress("NOTHING_TO_INLINE")
import kotlin.reflect.KProperty
interface Debounced<T> {
var value: T
}
inline operator fun <T> Debounced<T>.getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
inline operator fun <T> Debounced<T>.setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
var count by debounced<String>("zero", debounceMs = 100)
fun main() {
count = "one"
count = "one"
count = "ten"
count = "three"
println(count) // zero
Thread.sleep(150)
println(count) // three
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment