One Off the Slack: How Do We Have Immutable State?

Dmitry Suzdalev asked:

is there some kind of immutableStateOf(value)?

val state = when (orientation) {
  Orientation.Landscape -> animateDpAsState(32.dp)
  Orientation.Portrait -> immutableStateOf(16.dp)

I could use mutableStateOf(16.dp) of course, just thought maybe something more lightweight exists.

Google’s Adam Powell was slightly mystified:

why would you use a constant argument to animateDpAsState? 🤔

Dmitry then realized his trimmed-down example had a bug:

ah, actually there’s an if there, sorry: animateDpAsState(if (someFlag) 0.dp else 32.dp). otherwise the question is still valid.

Adam then offered:

I’d probably fold it into the when with something like

  when (orientation) {
    Landscape -> if (someFlag) 0.dp else 32.dp
    Portrait -> 16.dp

and as a bonus you can get animation between those two for things like window resizing changing the orientation

but no, there’s no immutableStateOf and you should never need one. Either use the constant directly, or if you’re making a late-binding decision and you want a snapshot read to occur more deeply in your UI somewhere, use a () -> T lambda instead of trying to construct a State<T> around something

Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!