Home > OS >  Composable State from Jetpack Compose execute these two states once or twice
Composable State from Jetpack Compose execute these two states once or twice

Time:11-05

I got a two states for handling a dynamic pop up screen component

var showPopUpScreen by remember { viewModel.popUpScreenIsOpen }
var popUpType by remember { viewModel.popUpScreenType }

but when I change the value of these mutableState-values when opening the pop up component like this:

fun OpenPopUpScreen(type: BasePopUpScreen) {
    popUpScreenType.value = type
    popUpScreenIsOpen.value = true
}

will this composable function get executed twice (which is performance heavy) or will it be smart enough to know that these values are set at once so execute my pop up render function only once?

Extra code info:

fun LiveTrainingScreen(viewModel: LiveTrainingViewModel = viewModel()) {
// lots of code and then:
        var showPopUpScreen by remember { viewModel.popUpScreenIsOpen }
        var popUpType by remember { viewModel.popUpScreenType }

        //pop up container
        if(showPopUpScreen) {

            Row(modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.6f))
                .zIndex(11f), verticalAlignment = Alignment.CenterVertically) {
                Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {

                    DyanmicPopUpScreenLiveTraining(popUpScreenTypeInfo = popUpType, viewModel = viewModel)

                } // pop up main column

            } // end pop up screen row

        } // end if pop up screen
}

CodePudding user response:

I believe the recomposition starts right after both have changed as the compose guide says:

"Recomposition is optimistic and may be canceled." [source: https://developer.android.com/jetpack/compose/mental-model]

in which means the recomposition will be canceled as the other parameter is assigned and you will see the change in state in UI in means of both values.

However, it is a better approach to save the UI state inside a data class and remember the data class directly. that way, you change both variables and the composition resets as the data class changes. plus, rather than remembering the data class, hoist the state in a ViewModel and you will good to go.

CodePudding user response:

I think compose is smart enough to identify the changes and react on it. As per your question

  • once you set first value it will start changes compose views which are dependent on it
  • And suppose considering complex view previous recomposition process is going on, after setting second value previous recomposition will get cancelled and compose will recompose your screen with updated both values.

So effectively we can Recomposition will happen once only.

  • Related