I wanna use a state holder class to keep some app ...
# compose
p
I wanna use a state holder class to keep some app level state things, for example, if a dialog must be displayed. For that, I added title and message variables in the app state holder class. When I set them to a value different from null, that should display a dialog on my app, because I'm checking if these variables are different from null for displaying it on my screen composable. Something is not working because when I set these variables to a value different from null nothing happens. It seems that recomposition is not being started. More on the thread...
This is the app state composable and the remember function I use to remember it:
Copy code
val appStateHolder = rememberAppStateHolder()
Copy code
@Composable
fun rememberAppStateHolder(
    navController: NavHostController = rememberNavController(),
    dialogTitle: StringResource? = null,
    dialogMessage: StringResource? = null,
): AppStateHolder {
    return remember(
        navController,
        dialogTitle,
        dialogMessage
    ) {
        AppStateHolder(
            navController = navController,
            dialogTitle = dialogTitle,
            dialogMessage = dialogMessage
        )
    }
}

@Stable
class AppStateHolder(
    val navController: NavHostController = NavHostController(),
    var dialogTitle: StringResource? = null,
    var dialogMessage: StringResource? = null
) {
    // UI State
    val currentDestination: NavDestination?
        @Composable get() = navController
            .currentBackStackEntryAsState().value?.destination

    fun isDialogEnabled(): Boolean {
        return (dialogTitle != null || dialogMessage != null)
    }

    // UI logic
    fun navigate(route: String) {
        navController.navigate(route)
    }

    fun showDialog(dialogTitle: StringResource, dialogMessage: StringResource) {
        this.dialogTitle = dialogTitle
        this.dialogMessage = dialogMessage
    }

    fun hideDialog() {
        this.dialogTitle = null
        this.dialogMessage = null
    }
}
This is how I check if the dialog should be displayed:
Copy code
if (appStateHolder.isDialogEnabled()) {
    MessageDialog(
        title = stringResource(Res.string.about),
        message = stringResource(Res.string.about_message),
        onCloseRequest = { appStateHolder.hideDialog() }
    )
}
This is how I set the dialog values to different of null:
Copy code
appStateHolder.showDialog(title, message)
z
Your mutable state holder properties aren’t backed by snapshot state. You need mutableStateOf
p
you mean mutablestateof in the internal variables? is not enought with having the entire state holder being a mutablestateof?
z
Nope. This article talks about lists but the same applies to objects with mutable properties.
👍 2