Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and stop animation in Jetpack Compose

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?

like image 409
Bence Nagy Avatar asked Oct 22 '25 07:10

Bence Nagy


1 Answers

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)
                )
            )
        }
    }
}
like image 60
Gabriele Mariotti Avatar answered Oct 25 '25 01:10

Gabriele Mariotti