Junior — Middle
How can you track changes in state in Jetpack Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, state changes are tracked using special data types and mechanisms that automatically trigger UI redraws when the state changes.
Main methods:
- MutableState<T> — a wrapper around a value that notifies Compose of changes.
- Using the
rememberfunction to save state within a composition. - Using
StateandLiveDatafrom ViewModel, which Compose can observe.
Example:
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) {
Text("Clicked $count times")
}
}
Here, mutableStateOf creates an observable state. When count changes, Compose automatically redraws the button with the new value.