Search code examples
androidsplash-screenandroid-jetpack-composelottie

How to take animation time from Lottie json in Android?


At the moment I'm setting the delay as a constant, instead I want to take the time that is used in the json animation, how can this be done?

Here is code where i used constant:

val composableScope = rememberCoroutineScope()

Box(
    contentAlignment = Alignment.Center,
    modifier = Modifier.fillMaxSize()
) {

    LottieExample()
    composableScope.launch {
        delay(2000L)
        navController.navigate(viewModel.nextRoute) {
            popUpTo(0)
        }
    }
}

And here is the animation code itself:

@Composable
fun LottieExample() {

    val compositionResult: LottieCompositionResult = rememberLottieComposition(
        spec = LottieCompositionSpec.RawRes(R.raw.splash_with_background)
    )
    val progress by animateLottieCompositionAsState(
        composition = compositionResult.value,
        isPlaying = true,
        iterations = LottieConstants.IterateForever,
        speed = 1.0f
    )

    LottieAnimation(
        composition = compositionResult.value,
        progress = progress,
        modifier = Modifier.padding(all = 12.dp)
    )
}

Solution

  • Took compositionResult out of bounds and pull out the duration of the animation. Solved with next solution:

    val composableScope = rememberCoroutineScope()
    
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier.fillMaxSize()
    ) {
        val compositionResult: LottieCompositionResult = rememberLottieComposition(
            spec = LottieCompositionSpec.RawRes(R.raw.splash_with_background)
        )
        SplashScreenAnimation(compositionResult = compositionResult)
        composableScope.launch {
            delay(compositionResult.value?.duration?.toLong() ?: SPLASH_SCREEN_DURATION)
            viewModel.destination.firstOrNull()?.let { route ->
                navController.clearBackStackAndNavigateTo(route)
            }
        }
    }