Search code examples
kotlinstatewordpress-jetpack

Jetpack compose recomposition


I have issue I need to understand how to solve it please ..

I have button inside fragment that open compose overlay.

    private fun onClicked() {
    binding.composeView.setContent {
        cashDialogComposableView()
    }
}

What i want to do is to create a compose view that handle the overlay states itself .. no need for anything to call this overlay as simple as calling this line cashDialogComposableView and pass the overlay model.

so this the compose screen code:

@Composable
fun cashDialogComposableView() {
val cashDialogViewModel: CashDialogViewModel = viewModel()
cashDialogViewModel.changeCashDialogVisibility(true)

when (cashDialogViewModel.cashDialogVisibility.collectAsState().value) {
    true -> {
        cashDialogScreen(
            cashDialogModel = CashDialogModel(
                title = "",
                subtitle = "",
                confirmButtonAction = {},
                cancelButtonAction = {},
                icon = R.drawable.error_icon
            )
        ) {
            cashDialogViewModel.changeCashDialogVisibility(false)
        }
    }
    false -> {
        return
    }
}

}

When user click on the button it call this method .. and the first state is true .. and when the user dismiss the overlay it will change the state to false and the overlay will hide. and when the user click again the first line is change state to true .. but this is not happened .. what happened is when the user click on dismiss the state change and then the screen recompose and call again cashDialogViewModel.changeCashDialogVisibility(true) this line so after the overlay hidden he shown again .

I have tried a lot of things like LaunchedEffect and `DisposableEffect.

How to solve this problem?


Solution

  • I found the solution.

    Compose view called once when you click the button because nothing happened after click the button that trigger the recomposition and re call the method .. to do that without handle state or any thing just call compose.setContent={} when you dismiss the overlay .. this code act as reset the compose and then every click will treat compose as first time clicking.

           private fun onClicked() {
            binding.composeView.setContent {
                cashDialogComposableView(){
    binding.composeView.setContent{}
    }
            }
        }
    

    and pass onDismiss call back to cashDialogComposableView so whenever you click the button the overlay will opened .. and when you close the overlay the compose view will reset as first time. so now you can put all code and state handled encapsulated inside one method without handle anything from outside this method just call the method and pass whatever you want