Last active
August 22, 2018 12:23
-
-
Save justasm/69a66dd95a5ffeee16ec8dbe988e6ab4 to your computer and use it in GitHub Desktop.
Debounced property delegate Android implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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