This [Animatable] function creates a Color value holder that automatically animates its value when the value is changed via [animateTo].
AnimatableColor
fun AnimatableColor() {
@Composable
fun animate(
targetValue: Color,
animationSpec: AnimationSpec<Color>,
onFinished: (Color) -> Unit,
): Color {
// Creates an Animatable of Color, and remembers it.
val color = remember { Animatable(targetValue) }
val finishedListener = rememberUpdatedState(onFinished)
// Launches a new coroutine whenever the target value or animation spec has changed. This
// automatically cancels the previous job/animation.
LaunchedEffect(targetValue, animationSpec) {
color.animateTo(targetValue, animationSpec)
// Invokes finished listener. This line will not be executed if the job gets canceled
// halfway through an animation.
finishedListener.value(targetValue)
}
return color.value
}
}