简体   繁体   中英

Jetpack Compose - Play complex animation on state change

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 }
        }
    }
}

LaunchedEffect is the answer:

@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")
    LaunchedEffect(state) {
        if (state == DesiredState) {
            scope.launch {
                animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
                animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM