https://kotlinlang.org logo
Title
j

Justin Yue

09/06/2021, 9:34 PM
I have
mutableStateListOf()
object, which I named days, that holds
data class Cell(val text: String, var isSelected: Boolean).
When I want to change the isSelected status, I have to reassign one element to a new Cell with the updated boolean. I would prefer to just reassign one element's isSelected boolean, but that doesn't seem to work. Does anybody know why?
In one of my view models, I have this code:
var days = mutableStateListOf(
        Cell("Sun", false),
        Cell("Mon", false),
        Cell("Tue", false),
        Cell("Wed", false),
        Cell("Thu", false),
        Cell("Fri", false),
        Cell("Sat", false)
    )
And I have this function to change the boolean in a Cell:
fun changeDaySelection(index: Int) {
//        days[index].isSelected = !days[index].isSelected <- this line does cause recomposition 
        days[index] = Cell(days[index].text, !days[index].isSelected) // <- this line does cause recomposition
    }
Not entirely sure why the commented line wouldn't work
c

CLOVIS

09/06/2021, 10:50 PM
Boolean
is not a
State
.
var isSelected: State<Boolean>
should work, but I don't know if it's good practice.
Another solution:
data class Cell(..., val isSelected: Boolean)
// note the val

var days by remember { mutableStateListOf(...) }
...
days = days[index].copy(isSelected = !days[index].isSelected)
Eg: Compose knows only when you use
=
on the State class.
j

Justin Yue

09/06/2021, 10:58 PM
Makes sense. I agree that making
isSelected: State<Boolean>
might not be the best approach, and I'll try out the 2nd solution. Thank you for your help.
z

Zach Klippenstein (he/him) [MOD]

09/07/2021, 2:31 PM
You can do something like this to avoid having the state type in your api:
class Cell {
  var isSelected: Boolean by mutableStateOf(false)
}
🙌 1