Junior — Middle
How can you monitor changes in the state of a collection displayed in the interface using Jetpack Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, to monitor changes in the state of a collection displayed in the interface, State or MutableState are usually used together with collections that support reactivity, such as SnapshotStateList.
To automatically update the interface when the collection changes, you need to:
- Use
mutableStateListOf()to create an observable list. - Make changes to this list (add, remove items).
- Access this list directly in Composable functions.
Example:
val items = remember { mutableStateListOf("Item 1", "Item 2") }
Column {
items.forEach { item ->
Text(text = item)
}
Button(onClick = { items.add("New Item") }) {
Text("Add item")
}
}
When a new item is added to items, Compose automatically redraws the interface, reflecting the changes.
Thus, the key is to use special observable collections and work with them through State.