Jetpack recomposition behavior

149 Views Asked by At

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?

  1. 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")
    }
}
  1. 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")
        }
    }
}
1

There are 1 best solutions below

2
On BEST ANSWER

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