Last active
July 30, 2021 14:57
MutableStateList Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This one updates the list on click but since the state handling framework sees the same reference | |
* it doesnt know that the state is updated, so no recompose | |
*/ | |
@Composable | |
fun StateOfMutableList() { | |
// Tip: If we can cast to non mutable state we're doing it wrong. Need to call [MutableState].setValue to recompose | |
val state: State<MutableList<Int>> = remember { mutableStateOf(listOf(1, 2, 3, 4).toMutableList()) } | |
Column { | |
state.value.forEachIndexed { index, num -> | |
Text(num.toString(), Modifier.clickable { state.value[index] += 1 }) | |
} | |
} | |
} | |
/** | |
* This works because we're calling set on [MutableState.value] not [MutableList.set], so it knows to recompose | |
*/ | |
@Composable | |
fun ListOfMutableState() { | |
val state: List<MutableState<Int>> = remember { listOf(1, 2, 3, 4).map { mutableStateOf(it) } } | |
Column { | |
state.forEachIndexed { index, num -> | |
Text(num.value.toString(), Modifier.clickable { state[index].value += 1 }) | |
} | |
} | |
} | |
/** | |
* Think this is the proper way to handle. A subclass of mutable list that handles state updates properly is built in | |
* Gets proper recomposition and can treat the object as a mutable list so you dont have to think about it | |
*/ | |
@Composable | |
fun MutableStateList() { | |
val state: SnapshotStateList<Int> = remember { | |
mutableStateListOf(1, 2, 3, 4) | |
} | |
// Can upcast to use as mutable list and forget about state management entirely | |
val nums = state as MutableList<Int> | |
Column { | |
nums.forEachIndexed { index, num -> | |
Text(num.toString(), Modifier.clickable { state[index] += 1 }) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment