Junior — Middle
How to implement reactive data updates using LiveData in Jetpack Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, the observeAsState() function is used for reactive UI updates based on data from LiveData. It converts LiveData into Compose State, allowing the interface to automatically update when data changes.
Example:
@Composable
fun UserNameDisplay(viewModel: UserViewModel) {
val userName by viewModel.userNameLiveData.observeAsState("")
Text(text = "User name: $userName")
}
Here, userNameLiveData is a LiveData<String> from the ViewModel. When the LiveData value changes, Compose automatically redraws the Text with the new username.