Hey everyone!
I'm working on an animation issue in my app and could use some help. Here's the problem I'm facing:
I have a property inside my ViewModel that regularly updates with values like +500, -100, etc. What I want to do is animate this property value when it changes (so instead of jumping directly to 500, it animates smoothly).
More in 🧵
Abdullah Musa
03/31/2025, 10:22 AM
My current "solution" looks like this, but it causes too many recompositions:
Copy code
// ViewModel
var elevation by mutableIntStateOf(0)
private set
// Composable
val elevation by animateIntAsState(
targetValue = viewModel.elevation,
animationSpec = tween(durationMillis = 500, easing = FastOutSlowInEasing),
label = "elevationAnimation",
)
Abdullah Musa
03/31/2025, 10:25 AM
Also, this animated value needs to be used in a few places:
1. Displayed as text – This part is already handled using a Canvas without causing unnecessary recompositions.
2. Displaying images based on value ranges – I still haven't found an optimal solution for this.
My current solution for 2. is:
Copy code
backgroundImages.forEach {
if (elevation in it.renderRange) {
Image(...)
}
}
o
onatyr
03/31/2025, 1:30 PM
Hi same problem here, just answering for notifications in case someone has a solution. Good luck to us
z
Zach Klippenstein (he/him) [MOD]
03/31/2025, 2:51 PM
You could use
derivedStateOf
to calculate which range you’re in and then only read the derived state in composition
a
Abdullah Musa
04/01/2025, 6:26 PM
That could work for the ranges without animation. However frequent recomposition occurs if I'm animating like this:
>
Copy code
val elevation by animateIntAsState(targetValue = viewModel.elevation, ...)