状态更改时应激发重新组合在代码示例中,一个状态更改但重新组合未激发,但在代码示例中,两个状态更改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")
}
}
}
1条答案
按热度按时间6rqinv9w1#
如何使代码样本在状态改变时重新组合?
您应该在第一次合成期间使用
SideEffect
来改变状态,以便使这些更改“生效”:进一步阅读:https://developer.android.com/jetpack/compose/side-effects