Home > Enterprise >  How to wait for the end of the animation correctly?
How to wait for the end of the animation correctly?

Time:02-05

I know that I can track the moment when lottie animation is completed using progress. But the problem is that I want to start a new screen at the moment when the animation is completely finished.

Here is the code of my animation

@Composable
fun AnimatedScreen(
    modifier: Modifier = Modifier,
    rawId: Int
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = modifier.fillMaxSize()
    ) {
        val compositionResult: LottieCompositionResult = rememberLottieComposition(
            spec = LottieCompositionSpec.RawRes(rawId)
        )
        AnimatedScreenAnimation(compositionResult = compositionResult)
    }
}

@Composable
fun AnimatedScreenAnimation(compositionResult: LottieCompositionResult) {

    val progress by animateLottieCompositionAsState(composition = compositionResult.value)

    Column {
        if (progress < 1) {
            Text(text = "Progress: $progress")
        } else {
            Text(
                modifier = Modifier.clickable { },
                text = "Animation is done"
            )
        }
        LottieAnimation(
            composition = compositionResult.value,
            progress = progress,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.FillBounds
        )
    }
}

And here is code of my screen where i want to wait for the end of the animation and then go to a new screen:

@Composable
fun SplashScreen(
    navController: NavController,
    modifier: Modifier = Modifier,
    viewModel: SplashScreenViewModel = getViewModel()
) {
    val resIdState = viewModel.splashScreenResId.collectAsState()

    val resId = resIdState.value
    if (resId != null) {
        AnimatedScreen(modifier = modifier, rawId = resId)
    }

    LaunchedEffect(true) {
        navigate("onboarding_route") {
            popUpTo(0)
        }
    }
}

CodePudding user response:

I used the progress & listened to it's updates & as soon as it reaches 1f I'll call my function.

Example:

@Composable
fun Splash() {
    LottieTest {
        // Do something here
    }
}

@Composable
fun LottieTest(onComplete: () -> Unit) {
    val composition: LottieCompositionResult =
        rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.camera))
    val progress by animateLottieCompositionAsState(
        composition.value,
        iterations = 1,
    )

    LaunchedEffect(progress) {
        Log.d("MG-progress", "$progress")
        if (progress >= 1f) {
            onComplete()
        }
    }

    LottieAnimation(
        composition.value,
        progress,
    )
}

Note: This is just the way I did it. The best way is still unknown(to me atleast). I feel it lacks the samples for that.

Also, You can modify a lot from this & just concentrate on the core flow.

  •  Tags:  
  • Related