Play the compose animation once time (not on navigate up)

Viewed 26

I have an application with 2 screens: (ScreenA and ScreenB)

I created a translation animation that launches at the start of the app on screenA.

val horizontalBias = remember { Animatable(0f) }
val alignment by derivedStateOf { BiasAlignment.Horizontal(horizontalBias.value) }
LaunchedEffect(key1 = 1) {
    horizontalBias.animateTo(
        targetValue = -1f,
        animationSpec = tween(
            durationMillis = durationMillis,
            delayMillis = delayMillis
        )
    )

}
Box(modifier = modifier)
{
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = alignment)
    {
...
    }
}

I would like this animation to play when launching the application but not when navigating up from screenB

I would also like the animation not play when the orientation of device change

Edit

I don't know if this is a good way but I found a solution that works:

var horizontalBias by rememberSaveable {
        mutableStateOf(0f)
    }
    val horizontalAnimatable = remember { Animatable(horizontalBias) }
    val alignment by derivedStateOf { BiasAlignment.Horizontal(horizontalAnimatable.value) }
    LaunchedEffect(true) {
        if (horizontalBias > -1f) {
            horizontalAnimatable.animateTo(
                targetValue = -1f,
                animationSpec = tween(
                    durationMillis = durationMillis,
                    delayMillis = delayMillis
                )
            )
            horizontalBias = -1f
        }
    }
1 Answers

For animation to run once you can keep a value in VieModel and

LaunchedEffect(key1 = viewModel.isAnimationRun) {
  if(!vieModel.isAnimationRun)
    horizontalBias.animateTo(
        targetValue = -1f,
        animationSpec = tween(
            durationMillis = durationMillis,
            delayMillis = delayMillis
        )
    )
    viewModel.animationRun = true
  }
}
Related