Created
February 27, 2021 19:49
-
-
Save jknair0/64889217aae5678dc3d154701fad3e46 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* Copyright (c) 2021 JayaKrishnan Nair K | |
* All rights reserved. | |
*/ | |
package tech.jknair.uibase.utils | |
import kotlin.properties.ObservableProperty | |
import kotlin.properties.ReadWriteProperty | |
import kotlin.reflect.KProperty | |
abstract class ValueChangeDelegate<V>( | |
initialValue: V, | |
private val distinct: Boolean = false | |
) : ObservableProperty<V>(initialValue) { | |
override fun beforeChange(property: KProperty<*>, oldValue: V, newValue: V): Boolean { | |
return !distinct || oldValue != newValue | |
} | |
} | |
inline fun <V> valueChange( | |
distinct: Boolean = false, | |
initialValue: V, | |
crossinline onChangeCallback: (newValue: V) -> Unit | |
): ReadWriteProperty<Nothing, V> { | |
return object: ValueChangeDelegate<V>(initialValue) { | |
override fun afterChange(property: KProperty<*>, oldValue: V, newValue: V) { | |
onChangeCallback(newValue) | |
} | |
} | |
} | |
inline fun <V> valueChange( | |
initialValue: V, | |
crossinline onChangeCallback: (newValue: V) -> Unit | |
): ReadWriteProperty<Nothing, V> { | |
return object: ValueChangeDelegate<V>(initialValue) { | |
override fun afterChange(property: KProperty<*>, oldValue: V, newValue: V) { | |
onChangeCallback(newValue) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment