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?
- Below code does not fire recomposition
@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")
}
}
- But this code fire recomposition upon Button Click
@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")
}
}
}
You should use a
SideEffect
to mutate state during first composition in order for these changes to take "effect" :Further reading : https://developer.android.com/jetpack/compose/side-effects