How do I make rememberSaveable work inside movableContentOf?

Viewed 131

I made two similar navigation @Composables with a slot for content, one of them is used depending on the screen size class. I also use rememberSaveable inside the content to handle screen rotation. The problem is, without movableContentOf, their state is handled as separate, but with it, the saved state is gone after every screen rotation. A simplified example:

Column(
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally,
) {

    val content = remember {
        movableContentOf {
            var a by remember { mutableStateOf(false) }
            Checkbox(a, { a = it })
            var b by rememberSaveable { mutableStateOf(false) }
            Checkbox(b, { b = it })
        }
    }

    var switch by rememberSaveable { mutableStateOf(false) }
    Checkbox(switch, { switch = it })
    if (switch) Row { content() } else Column { content() }

}

Mode switching works just fine, but only the upper checkbox keeps its state after screen rotation.

1 Answers

This is intended behaviour: you create movableContentOf inside remember, which means it's gonna be recreated on rotation.

You can store it inside a view model, but if you need to do so, you can store your data there as well, which makes storing movableContentOf redundant: in this case, re-creating it in remember is perfectly fine.

Related