5

How do I play a complex animation using coroutine on switching to a particular state?

@Composable
fun SomeView(viewModel: SomeViewModel) {
    val state by viewModel.stateFlow.collectAsState()
    val scope = rememberCoroutineScope()
    
    ...
    val shutterAlpha by remember { mutableStateOf(0f) }
    Box(modifier = Modifier
        .fillMaxSize()
        .alpha(shutterAlpha)
        .background(Color.Black)
    )

    val transition = updateTransition(targetState = state, label = "label")
    <on transitioning to CaptureState> { // need actual condition check code here
        scope.launch {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Fried Rice
  • 3,295
  • 3
  • 18
  • 27
  • Why would you need to use a coroutine? Doesn't [documentation example](https://developer.android.com/jetpack/compose/animation#updateTransition) fits your case? – Phil Dukhov Nov 17 '21 at 00:01
  • I needed to play this animation sequence on state change, it's not a simple transition from one alpha value to another alpha value – Fried Rice Nov 17 '21 at 09:27

1 Answers1

2

LaunchedEffect is the answer:

@Composable
fun SomeView(viewModel: SomeViewModel) {
    val state by viewModel.stateFlow.collectAsState()
    
    ...
    val shutterAlpha by remember { mutableStateOf(0f) }
    Box(modifier = Modifier
        .fillMaxSize()
        .alpha(shutterAlpha)
        .background(Color.Black)
    )

    LaunchedEffect(state) {
        if (state == CaptureState) {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}
Fried Rice
  • 3,295
  • 3
  • 18
  • 27