Junior — Middle
Kuidas jälgida oleku muutusi Jetpack Compose'is?
sobes.tech AI
Vastus AI-lt
In Jetpack Compose, state changes are monitored 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 store state within the composition. - Using
StateandLiveDatafrom ViewModel, which Compose can observe.
Example:
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) {
Text("Pressed $count times")
}
}
Here, mutableStateOf creates an observable state. When count changes, Compose automatically redraws the button with the new value.