What if your app never lost user data even when the screen flips?
Why ViewModel creation in Android Kotlin? - Purpose & Use Cases
Imagine you are building an app that shows user data and updates it when the user interacts. Without ViewModel, you have to manually save and restore data every time the screen rotates or the app goes to the background.
This manual saving and restoring is slow and error-prone. You might forget to save some data or write complicated code to handle lifecycle changes. This leads to bugs and a poor user experience.
ViewModel automatically holds your app's data during configuration changes like screen rotations. It keeps your UI data safe and separate from UI controllers, so you write cleaner and more reliable code.
override fun onSaveInstanceState(outState: Bundle) {
outState.putString("name", userName)
}
override fun onCreate(savedInstanceState: Bundle?) {
userName = savedInstanceState?.getString("name") ?: ""
}class UserViewModel : ViewModel() { val userName = MutableLiveData<String>() } // Activity or Fragment just observes userName without manual saving
With ViewModel, your app can smoothly handle screen rotations and lifecycle changes without losing data or crashing.
Think of a shopping app where the user fills a form. If the screen rotates, the form data stays intact because ViewModel keeps it safe.
Manual data saving on lifecycle changes is hard and buggy.
ViewModel keeps UI data safe automatically during these changes.
This leads to cleaner code and better user experience.
Practice
ViewModel in Android development?Solution
Step 1: Understand ViewModel role
A ViewModel is designed to hold UI data safely during configuration changes like screen rotations.Step 2: Compare options
Only To store and manage UI-related data in a lifecycle conscious way describes this purpose correctly; others describe unrelated tasks.Final Answer:
To store and manage UI-related data in a lifecycle conscious way -> Option CQuick Check:
ViewModel purpose = store UI data safely [OK]
- Confusing ViewModel with UI layout classes
- Thinking ViewModel handles user input directly
- Assuming ViewModel manages network calls
Solution
Step 1: Recall Kotlin class syntax
Kotlin uses a colon (:) to extend a class and parentheses for constructor calls.Step 2: Check each option
class MyViewModel : ViewModel() {} uses correct Kotlin syntax for extending ViewModel; others use Java syntax or invalid declarations.Final Answer:
class MyViewModel : ViewModel() {} -> Option BQuick Check:
Kotlin inheritance uses ':' and parentheses [OK]
- Using Java syntax 'extends' in Kotlin
- Declaring ViewModel as a function
- Assigning ViewModel to a val without class
counter.value is printed after increment() is called twice?
class CounterViewModel : ViewModel() {
val counter = MutableLiveData(0)
fun increment() {
counter.value = (counter.value ?: 0) + 1
}
}Solution
Step 1: Understand initial value and increment
counter starts at 0; each increment adds 1 to current value.Step 2: Calculate after two increments
After first call: 0 + 1 = 1; after second call: 1 + 1 = 2.Final Answer:
2 -> Option AQuick Check:
Two increments from 0 = 2 [OK]
- Forgetting to unwrap nullable value
- Assuming counter resets each time
- Confusing LiveData with normal variable
class SampleViewModel : ViewModel() {
val data = MutableLiveData<String>()
fun updateData(newData: String) {
data.value = newData
}
fun getData(): String {
return data.value
}
}Solution
Step 1: Check LiveData type and usage
MutableLiveData<String> can hold String values; updateData() correctly sets value.Step 2: Analyze getData() return type
data.value is nullable String?, but getData() returns non-nullable String, causing a type mismatch.Final Answer:
getData() returns nullable String but declared as non-nullable -> Option DQuick Check:
LiveData value is nullable; return type must match [OK]
- Ignoring nullable type of LiveData.value
- Thinking ViewModel must be abstract
- Believing LiveData can't hold String
Solution
Step 1: Identify reactive data holder
MutableLiveData<List<String>> allows UI to observe changes and update reactively.Step 2: Check update method correctness
class UserViewModel : ViewModel() {\n val users = MutableLiveData<List<String>>(emptyList())\n fun addUser(name: String) {\n users.value = users.value?.plus(name)\n }\n} uses users.value?.plus(name) to add a user immutably and update LiveData, which is correct.Step 3: Review other options
class UserViewModel : ViewModel() {\n val users = mutableListOf<String>()\n fun addUser(name: String) {\n users.add(name)\n }\n} uses mutableList but not LiveData, so UI won't update reactively. class UserViewModel : ViewModel() {\n var users = listOf<String>()\n fun addUser(name: String) {\n users += name\n }\n} uses var list but no LiveData. class UserViewModel : ViewModel() {\n val users = LiveData<List<String>>()\n fun addUser(name: String) {\n users.value = listOf(name)\n }\n} tries to instantiate LiveData directly, which is abstract and invalid.Final Answer:
class UserViewModel : ViewModel() {\n val users = MutableLiveData<List<String>>(emptyList())\n fun addUser(name: String) {\n users.value = users.value?.plus(name)\n }\n} -> Option AQuick Check:
Use MutableLiveData with immutable updates for reactive UI [OK]
- Using mutableList without LiveData for UI data
- Trying to instantiate LiveData directly
- Modifying list without updating LiveData value
Ready to prove it?
Pass the test and this pattern moves unknown
