Skip to content

Instantly share code, notes, and snippets.

@ggrell
Forked from gpeal/uniqueObservable.kt
Created April 22, 2021 21:07
Show Gist options
  • Save ggrell/8cfc285abe9efa9ec6b7e610136565bf to your computer and use it in GitHub Desktop.
Save ggrell/8cfc285abe9efa9ec6b7e610136565bf to your computer and use it in GitHub Desktop.
Unique Observable
/**
* Like Delegates.observable except it only calls the callback when the value actually changes.
*/
public inline fun <T> uniqueObservable(initialValue: T, emitInitial: Boolean = false, crossinline onChange: (value: T) -> Unit): ReadWriteProperty<Any?, T> {
if (emitInitial) onChange(initialValue)
return object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) {
if (oldValue != newValue) onChange(newValue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment