Skip to content

Instantly share code, notes, and snippets.

@andreymusth
Created August 13, 2021 14:20
Show Gist options
  • Save andreymusth/e807895d3539d55ada4fbd9c69caae30 to your computer and use it in GitHub Desktop.
Save andreymusth/e807895d3539d55ada4fbd9c69caae30 to your computer and use it in GitHub Desktop.
class AnimatedValue<T>(
initial: T,
private val spec: AnimationSpec,
private val updateCallback: (value: T) -> Unit,
private val evaluation: (fraction: Float, startValue: T, endValue: T) -> T
) {
private var animator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = spec.duration
interpolator = spec.interpolator
addUpdateListener { currentValue = evaluation(it.animatedFraction, startValue, value) }
}
init {
updateCallback(initial)
}
var value: T = initial
set(value) {
if (field != value) {
field = value
animate()
}
}
private var startValue: T = initial
private var currentValue: T = initial
set(value) {
field = value
updateCallback(value)
}
private fun animate() {
startValue = currentValue
animator.cancel()
animator.start()
}
fun dispose() {
animator.cancel()
animator.removeAllListeners()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment