当状态发生变化时,应触发重新组合。在代码示例中,一个状态发生变化,但重新组合不会触发,但在代码示例的ButtonClick上发生的两个状态变化和重新组合会触发。
如何使代码样本在状态变化时重新组合?
- 以下代码不触发重新组合
@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")
}
}
- 但此代码在单击按钮时触发重新组合
@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")
}
}
}
如何使代码样本在状态更改时重新组合?
您应该在第一次合成期间使用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