Skip to content

Instantly share code, notes, and snippets.

@pablisco
Last active May 23, 2024 11:01
Show Gist options
  • Save pablisco/25613d10a5750ff7621ec793a0218d62 to your computer and use it in GitHub Desktop.
Save pablisco/25613d10a5750ff7621ec793a0218d62 to your computer and use it in GitHub Desktop.
Compose State Extensions
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
fun <T> debouncedMutableStateOf(
initialValue: T,
debounceTime: Long = 500,
): MutableState<T> {
var lastUpdate = now()
return mutableStateOf(initialValue).bimap(
read = { it },
write = { newValue: T ->
now().let { now ->
newValue.takeIf { now - lastUpdate > debounceTime }
?.also { lastUpdate = now } ?: value
}
}
)
}
fun <T, R> State<T>.map(block: (T) -> R): State<R> =
object : State<R> {
override val value: R get() = this@map.value.let(block)
}
fun <T, R> MutableState<T>.bimap(
read: (T) -> R,
write: State<T>.(R) -> T,
): MutableState<R> =
object : MutableState<R> {
override var value: R
get() = this@bimap.value.let(read)
set(value) {
this@bimap.value = write(value)
}
override fun component1(): R = value
override fun component2(): (R) -> Unit =
{ this@bimap.value = write(it) }
}
private fun now() = System.currentTimeMillis()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment