Home > Enterprise >  Jetpack Compose: MutableState<Boolean> not working as intended
Jetpack Compose: MutableState<Boolean> not working as intended

Time:01-25

In our Android app we want to introduce Compose to a simple debug screen, where we can enable/disable SharedPreferences. I'm trying to get that running using Compose' interface MutableState - but it does not work how I think it does. My plan is to temporarily use MutableState to set a boolean in SharedPreferences (before migrating to DataStore later).

Here is what I had in mind:

private class MyOwnState(startWith: Boolean) : MutableState<Boolean> {
    override var value: Boolean = startWith
    override fun component1(): Boolean = value
    override fun component2(): (Boolean) -> Unit = { value = it }
}

// then, in composable:
var value by remember { MyOwnState(false) }

Of course in real life I would overwrite the getter setter of the value - but this example is enough, because it does not work. The state change is not propagated and the UI is not updated.

To illustrate this, I but together the code snippets by remember { mutableStateOf(false) } and by remember { MyOwnState(false) }. The first one works (switch is updated), the second one does not.

Full code:

@Composable
fun SomeStateExamples() {
    Column {
        SwitchWorks()
        SwitchDoesNotWork()
    }
}

@Composable
fun SwitchWorks() {
    var value by remember { mutableStateOf(false) }
    Switch(checked = value, onCheckedChange = { value = it })
}

@Composable
fun SwitchDoesNotWork() {
    var value by remember { MyOwnState(false) }
    Switch(checked = value, onCheckedChange = { value = it })
}


private class MyOwnState(startWith: Boolean) : MutableState<Boolean> {
    override var value: Boolean = startWith
    override fun component1(): Boolean = value
    override fun component2(): (Boolean) -> Unit = { value = it }
}

The first switch is togglable, the second one is not:

first switch works, second one does not

What am I missing? The MutableState interface is pretty simple, and stable - and I didn't find any extra methods (aka invalidate, notifyListeners, ...) that I need to call.

Thank you for your help!

  •  Tags:  
  • Related