Junior — Middle
Milliseid Jetpack ViewModel komponente kasutate andmete ja UI oleku haldamiseks?
sobes.tech AI
Vastus AI-lt
To manage data and UI state in Jetpack ViewModel, the following components are typically used:
-
LiveData — observable data that automatically updates the UI upon changes. Enables a reactive approach.
-
MutableLiveData — a mutable version of LiveData, used within the ViewModel to update data.
-
StateFlow / SharedFlow (from Kotlin Coroutines) — modern alternatives to LiveData for managing state and events with coroutine support.
-
SavedStateHandle — allows saving and restoring the ViewModel's state when the UI is recreated, such as during screen rotation.
Example of using LiveData in a ViewModel:
class MyViewModel : ViewModel() {
private val _text = MutableLiveData<String>()
val text: LiveData<String> = _text
fun updateText(newText: String) {
_text.value = newText
}
}