0
0
Android Kotlinmobile~5 mins

State in ViewModel in Android Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of ViewModel in Android development?
ViewModel holds and manages UI-related data in a lifecycle-conscious way. It survives configuration changes like screen rotations, keeping the UI state intact.
Click to reveal answer
beginner
How does MutableLiveData help in managing state inside a ViewModel?
MutableLiveData allows the ViewModel to hold data that can be observed by the UI. When data changes, the UI updates automatically.
Click to reveal answer
intermediate
Why should UI state be stored in ViewModel instead of Activity or Fragment?
Storing UI state in ViewModel prevents data loss during configuration changes and separates UI logic from UI controllers, making code cleaner and more testable.
Click to reveal answer
advanced
What is the difference between LiveData and StateFlow in ViewModel state management?
LiveData is lifecycle-aware and designed for UI observation. StateFlow is a Kotlin Flow that holds state and supports coroutines, offering more flexibility and modern reactive patterns.
Click to reveal answer
intermediate
How do you update state inside a ViewModel using MutableStateFlow?
You update the state by assigning a new value to the MutableStateFlow variable, for example: _state.value = newValue. Observers get notified automatically.
Click to reveal answer
What happens to ViewModel data when the device rotates?
AData is preserved and reused
BData is lost and reset
CViewModel is destroyed and recreated
DUI crashes
Which class is commonly used inside ViewModel to hold observable UI state?
ABundle
BIntent
CMutableLiveData
DView
Which of these is a benefit of using StateFlow over LiveData?
ASupports coroutines and reactive streams
BNot lifecycle-aware
CWorks only with Java
DCannot hold state
Where should you NOT store UI state in Android apps?
AViewModelStore
BViewModel
CFragment
DActivity
How do UI components get notified of state changes in ViewModel?
ABy polling the ViewModel
BThrough observers on LiveData or StateFlow
CBy restarting the Activity
DBy manual refresh
Explain how ViewModel helps manage UI state during device rotation.
Think about what happens when the screen rotates and how ViewModel keeps data safe.
You got /3 concepts.
    Describe the difference between LiveData and StateFlow for state management in ViewModel.
    Consider their usage and features in Kotlin and Android.
    You got /4 concepts.