I have two behaviors of an animation due to Flow s...
# compose
m
I have two behaviors of an animation due to Flow setup code, the only difference is how I launch Flow, code in thread.
c
@Mohamed Ibrahim can you edit your post to put the code in this thread please? https://kotlinlang.slack.com/archives/CJLTWPH7S/p1616265877303000
m
sure 😄
First setup that generate strange animation , which go and back between the value
Copy code
flow {
    (0..target).forEach {
        delay(interval)
        emit(it)
    }
}.onEach {
    animateFloat.animateTo(
        targetValue = (it.toFloat() / target) * 360f,
        animationSpec = tween(durationMillis = 1000, easing = FastOutSlowInEasing)
    )
}.launchIn(scope = scope)
----------------
Second code that generate the desired animation which animate progress indicator
Copy code
LaunchedEffect(key1 = animateFloat) {
    flow {
        (0..target).forEach {
            delay(interval)
            emit(it)
        }
    }.collect {
        animateFloat.animateTo(
            targetValue = (it.toFloat() / target) * 360f,
            animationSpec = tween(durationMillis = 1000, easing = FastOutSlowInEasing)
        )
    }
}
I could see that the way I launch Flow is the difference here, but why LaunchedEffect worked and the later didn’t.
d
The flow in the first snippet gets re-created when recomposed. The new flow gets launched while the previous flow is still emitting. The second snippet would only recreate the flow when the key to the
LaunchedEffect
changes. When it does, the previous job will be canceled. So you won't be seeing multiple flows competing to emit new target for the animation.
m
Thank you for the explanation, it make sense