Reputation: 755
When state changes recomposition should fire. In code sample one state changes but recomposition doesn't fire but in code sample two state changes onButtonClick and recomposition fires.
How to make code sample one to recompose on state change?
@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")
}
}
}
Upvotes: 1
Views: 163
Reputation: 9919
How to make code sample one to recompose on state change?
You should use a SideEffect
to mutate state during first composition in order for these changes to take "effect" :
@Composable
fun doSomething() {
var shouldDo by remember { mutableStateOf(false) }
if (shouldDo) {
Log.e("=======================", "shouldDo: $shouldDo")
}
SideEffect {
shouldDo = true
}
}
Further reading : https://developer.android.com/jetpack/compose/side-effects
Upvotes: 2