I need to run a function when this variable: val isEnabled by remember {}
updates, and I need to pass the same variable into that same function, when the function runs.
I know this code won't work, but its the closest thing I can get to what I want it to do.
see <-- HERE
WritePrefs() is a Composable, and returns a Unit type
val isEnabled = readPrefs("enabled")
val color = if (!isEnabled) ButtonGreen else ButtonRed
val isEnabled by remember { WritePrefs("enabled", isEnabled.toString()) } <-- HERE
Button(
onClick = {
val isEnabled = !isEnabled
}
)
This question's code: https://stackoverflow.com/questions/66048620/how-to-change-button-background-color-on-click
Does a button's code (outside the onClick) re-run every time you click it?
You're architecting your code wrong. In your compose code, you shouldn't be reading preferences, getting data from any source, or doing any work other than displaying UI. These things should all be part of your state, and your UI should be driven only by the state.
To answer your question- no, the code outside the onClick is not run when clicked. It is run only when a recompose is needed. Which is only when any state for the composable changes. Instead, you should have somewhere in your ViewModel a StateFlow with the value of the enablement state. You should collectAsState on that variable. Then whenever it changes, your button will be redrawn.