Alexander Maryanovsky
12/27/2023, 2:49 PMMutableState. When using state as a delegate you often have the compiler refuse to do smart casts (e.g. if (x != null) { x.function() } doesn’t compile). The alternative is to just assign the state value to the variable (i.e. var xState by remember { mutableStateOf(…) } and then val x = xState.value). A better alternative is to use destructuring on the state - it turns out MutableState.component2 returns a setter of the value. So you can do:
val (x, setX) = remember { mutableStateOf(...) }
and then you have the value in x (which smart casts will work on), and a setter in setX. This is particularly convenient with composables like TextField.Albert Chang
12/27/2023, 3:15 PMx won’t be updated even after you call the setter with a new value, which isn’t the case if you use var x by remember { mutableStateOf(…) }.Alexander Maryanovsky
12/27/2023, 3:28 PMoperator fun <T> MutableState<T>.component3() = this
and use
val (x, setX, xState) = remember { mutableStateOf(...) }
😉Kachinga Mulenga
12/28/2023, 8:03 AMZach Klippenstein (he/him) [MOD]
01/02/2024, 7:29 PMif let x = xState