Home > Mobile >  Multiple Animations are Not Launching At the Same Time in Jetpack Compose
Multiple Animations are Not Launching At the Same Time in Jetpack Compose

Time:07-20

I have 3 animations, but the top one launches first, then the other two, how do I get them all to launch at the same time? I tried putting them in the same coroutine scope but still getting same results.

LaunchedEffect(isItemInView) {
    scope.launch {
        coroutineScope {
            launch { // Even without the scope.launch, coroutineScope, launch lines, same effect
                bar1.animateTo(if (isItemInView) bar1EndLocation else bar1StartLocation)
                bar2.animateTo(if (isItemInView) bar2EndSize else bar2StartSize)
                bar3.animateTo(if (isItemInView) bar3EndSize else bar3StartSize)
            }
        }

    }
}
Column{
   Bar1(modifier = Modifier.offset(bar1.value.x.dp, bar1.value.y.dp)
   Bar2(modifier = Modifier.size(bar2.value.width.dp, bar2.value.height.dp)
   Bar3(modifier = Modifier.size(bar3.value.width.dp, bar3.value.height.dp)
}

Is there something Im doing wrong here?

CodePudding user response:

As per your code base, you are calling the animateTo function in a coroutine scope. Note that the animateTo function is a suspend function. As a result, the bar2#animateTo won't be executed until bar1#animateTo is executed.

To animate all of them together, you would need to use async-await (Ref: https://stackoverflow.com/a/57458479/5309486 )

launch {
    awaitAll(
        async { bar1.animateTo(if (isItemInView) bar1EndLocation else bar1StartLocation) }
        async { bar2.animateTo(if (isItemInView) bar2EndSize else bar2StartSize) }
        async { bar3.animateTo(if (isItemInView) bar3EndSize else bar3StartSize) }
    )
}

  • Related