简体   繁体   中英

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

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?

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) }
    )
}

You can also run animations at the same time by calling launch separately for each Animatable

LaunchedEffect(key1 = isItemInView) {
    launch { bar1.animateTo(if (isItemInView) bar1EndLocation else bar1StartLocation) }
    launch { bar2.animateTo(if (isItemInView) bar2EndSize else bar2StartSize) }
    launch { bar3.animateTo(if (isItemInView) bar3EndSize else bar3StartSize)}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM