Home > Enterprise >  How to start and stop animation in Jetpack Compose
How to start and stop animation in Jetpack Compose

Time:12-24

In Jetpack Compose I need to start rotating a Text, when it is clicked. A coroutine runs, and when it is done, the animation should stopped.

So far I have:

    var isRotating by remember { mutableStateOf(false) }
    val angle = animateFloatAsState(
        targetValue = if (isRotating) 360f else 0f,
        animationSpec = infiniteRepeatable(tween(2000, easing = LinearEasing))
    )

    Box(
        modifier = Modifier
            .graphicsLayer { rotationZ = angle.value }
            .clickable {
                isRotating = true
                coroutineScope.launch {
                    doSlowProcess()
                    isRotating = false
                }
            }
        ) {
            Text("START")
        }

The text "START" should rotating until the "doSlowProcess" runs. It starts the rotation, but when it ends, it does not stop, just starts rotating in the other way, slower, and when reaches 0° it flips 180 degrees, and goes on. If I click it again it does the correct rotation, but at 0° jumps 90° ahead. I guess these "anomalies" would disappear, if the rotation stop when "isRotating" becomes false. How should I correctly start and stop the rotation?

CodePudding user response:

You can use something different:

var isRotating by remember { mutableStateOf(false) }
val angle = remember {
    Animatable(0f)
}
LaunchedEffect(isRotating) {
    launch {
        if (isRotating) {
            angle.animateTo(
                targetValue = 360f,
                animationSpec = infiniteRepeatable(
                    tween(2000, easing = LinearEasing)
                )
            )
        }
    }
}
  • Related