airbnb / lottie-android

Render After Effects animations natively on Android and iOS, Web, and React Native
http://airbnb.io/lottie/
Apache License 2.0
34.92k stars 5.4k forks source link

Multiple urls doesn't start animation from the beginning #2516

Open davidcrottymonzo opened 1 month ago

davidcrottymonzo commented 1 month ago

Minimal example to reproduce:

Scaffold(modifier = Modifier.fillMaxSize()) { padding ->
                    var url by remember { mutableStateOf("https://assets3.lottiefiles.com/packages/lf20_FyWhBU.json") }
                    Column(Modifier.padding(padding)) {
                        Button(onClick = {
                            url = if (url == "https://assets3.lottiefiles.com/packages/lf20_FyWhBU.json") {
                                "https://assets2.lottiefiles.com/packages/lf20_NBpLbW.json"
                            } else {
                                "https://assets3.lottiefiles.com/packages/lf20_FyWhBU.json"
                            }

                        }) {
                            Text("Change animation")
                        }
                        Animation(
                            url = url,
                        )
                    }

                }

@Composable
fun Animation(url: String, isPlaying: Boolean = true, loop: Boolean = true) {
    val spec = LottieCompositionSpec.Url(url)
    val composition = rememberLottieComposition(spec)
    val progress by animateLottieCompositionAsState(
        composition = composition.value,
        isPlaying = isPlaying,
        restartOnPlay = false,
        iterations = if (loop) LottieConstants.IterateForever else 1
    )

Log.d("Animation", "url: $url progress: $progress")

    composition.value?.let {
        LottieAnimation(
            composition = composition.value,
            progress = { progress },
            modifier = Modifier
        )
    }
}

Describe the bug

When switching to a new url, the animation in the new url does not start from the beginning. You can see this in the logs:

Screenshot 2024-07-04 at 16 00 07

Steps To Reproduce Steps to reproduce the behavior:

  1. Copy above code into sample app.
  2. Run, observe animations not starting from start frames when tapping change animation button & in logs

Additional info

The main issue seems to be not being able to trigger this inside animateLottieCompositionFromState

        if (isPlaying && !wasPlaying && restartOnPlay) {
            animatable.resetToBeginning()
        }

For now you can workaround this by wrapping the entire block with a key, as remember doesn't work due to lottie holding onto these states via remember {} functions