android 喷气背包重组行为

unguejic  于 2022-11-27  发布在  Android
关注(0)|答案(1)|浏览(170)

状态更改时应激发重新组合在代码示例中,一个状态更改但重新组合未激发,但在代码示例中,两个状态更改onButtonClick和重新组合均激发
如何使代码样本在状态改变时重新组合?
1.以下代码不触发重新组合

@Composable
fun doSomething(){
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var shouldDo by remember{ mutableStateOf(false) }

    LaunchedEffect(context){
        scope.launch(Dispatchers.Default){
            //Fetch a data from dataSource
            //then change the state
            withContext(Dispatchers.Main){
                shouldDo = true
            }
        }
    }
    //Process the data when @shouldDo state changes to true
    if(shouldDo){
        Log.e("=======================", "shouldDo: $shouldDo")
    }
}

1.但此代码在单击按钮时触发重新组合

@Composable
fun doSomeOtherThing() {
    var shouldDo by remember{ mutableStateOf(false) }
    if(shouldDo){
        Log.e("=======================", "shouldDo: $shouldDo")
    }
    Box(modifier = Modifier.fillMaxSize()){
        Button(
            modifier = Modifier.align(Alignment.Center),
            onClick = {
                shouldDo = true
            }
        ) {
            Text(text = "Button")
        }
    }
}
6rqinv9w

6rqinv9w1#

如何使代码样本在状态改变时重新组合?
您应该在第一次合成期间使用SideEffect来改变状态,以便使这些更改“生效”:

@Composable
fun doSomething() {
    var shouldDo by remember { mutableStateOf(false) }
    if (shouldDo) {
        Log.e("=======================", "shouldDo: $shouldDo")
    }

    SideEffect {
        shouldDo = true
    }
}

进一步阅读:https://developer.android.com/jetpack/compose/side-effects

相关问题