Hello :wave: I have troubles to re-trigger an anim...
# compose
o
Hello 👋 I have troubles to re-trigger an animation when a state changes. I want to make a label appear from left (outside the screen bounds) to center. I can make it work the first time but when I change the state linked to this label, the animation isn't re-triggered. (code in 🧵)
1
Copy code
var mode by remember { mutableStateOf<GameRules.Mode?>(null) }
val modeLabel = when (mode) {
    is Time -> "time"
    is Moves -> "moves"
    is Endless -> "no limit"
    else -> "choose mode"
}

val windowWidth = LocalAppWindow.current.width.toFloat()
val modeLabelOffset = remember { Animatable(-windowWidth) }
LaunchedEffect(mode) {
    modeLabelOffset.animateTo(
        targetValue = 0f,
        animationSpec = tween(durationMillis = 1000, easing = FastOutSlowInEasing)
    )
}

Text(
    modeLabel,
    Modifier.padding(8.dp).offset(x = modeLabelOffset.value.dp),
    textAlign = TextAlign.Center
)
Given that I use the
mode
as key of my
LaunchedEffect
I would expect it to be relaunched. My understanding is that the
modeLabelOffset
state matches the
targetValue
so nothing changes. I can't figure out how I can reset such state to its initial value (
-windowWidth
) whenever the
mode
changes.
I found something (
snapTo
) working but I don't know if it's the good way to do it.
Copy code
LaunchedEffect(mode) {
    modeLabelOffset.snapTo(-windowWidth)
    modeLabelOffset.animateTo(
        targetValue = 0f,
        animationSpec = tween(durationMillis = 1000, easing = FastOutSlowInEasing)
    )
}
When doing this, I can very briefly see the label update BEFORE it's moved outside the screen which isn't perfect.
If you move the progress cursor manually, you'll see the glitch, "Choose a mode" changes to "60 seconds" for 1 frame then the label goes out of screen (as intended) and is properly animated to final position. I don't know why there is such intermediate frame 🤷 (If that matters, I'm running this on CfD, not Android)
a
Have you tried
remember(mode) { Animatable(-windowWidth) }
?
😍 1
👌 1
o
I feel so stupid to not have understand
remember
could take a
key
parameter… Exactly what I wanted! It seems to work smoothly now, without
snapTo
and without glitch. Thanks @Albert Chang 🙇