Bird
Raised Fist0
Android Kotlinmobile~20 mins

Why ViewModel survives configuration changes in Android Kotlin - Build It to Prove It

Choose your learning style10 modes available
Build: ViewModel Survival Demo
This screen demonstrates how a ViewModel keeps data alive during configuration changes like screen rotation.
Target UI
-------------------------
| ViewModel Survival Demo |
-------------------------
| Count: 0               |
|                       |
| [Increment Count]      |
-------------------------
Display a count number starting at 0
Add a button labeled 'Increment Count' that increases the count by 1
Use ViewModel to store the count so it survives screen rotations
Show updated count immediately after increment
Starter Code
Android Kotlin
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : ComponentActivity() {
    private val viewModel: CounterViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val countTextView = findViewById<TextView>(R.id.countTextView)
        val incrementButton = findViewById<Button>(R.id.incrementButton)

        // TODO: Add code to observe ViewModel count and update UI
        // TODO: Add code to increment count on button click
    }
}

// TODO: Create CounterViewModel class here
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.Observer

class MainActivity : ComponentActivity() {
    private val viewModel: CounterViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val countTextView = findViewById<TextView>(R.id.countTextView)
        val incrementButton = findViewById<Button>(R.id.incrementButton)

        viewModel.count.observe(this) { count ->
            countTextView.text = "Count: $count"
        }

        incrementButton.setOnClickListener {
            viewModel.incrementCount()
        }
    }
}

class CounterViewModel : ViewModel() {
    private val _count = MutableLiveData(0)
    val count: LiveData<Int> = _count

    fun incrementCount() {
        val current = _count.value ?: 0
        _count.value = current + 1
    }
}

This app uses a ViewModel to hold the count number. The ViewModel stores the count in a MutableLiveData which allows the UI to observe changes and update automatically.

When the user taps the 'Increment Count' button, the ViewModel updates the count value. Because the ViewModel is tied to the activity lifecycle but survives configuration changes, the count value stays the same even if the screen rotates.

This means the UI will show the correct count after rotation without losing data or needing to save state manually.

Final Result
Completed Screen
-------------------------
| ViewModel Survival Demo |
-------------------------
| Count: 3               |
|                       |
| [Increment Count]      |
-------------------------
User taps 'Increment Count' button, count increases by 1 and updates on screen
User rotates device screen, count number remains the same and UI updates correctly
Stretch Goal
Add a reset button to set the count back to zero
💡 Hint
Add another Button labeled 'Reset Count' and create a ViewModel method to reset the count LiveData to 0

Practice

(1/5)
1. Why does a ViewModel survive configuration changes like screen rotations in Android?
easy
A. Because it is tied to the lifecycle of the activity or fragment and not recreated on configuration changes
B. Because it saves data to a file on disk automatically
C. Because it uses static variables to hold data
D. Because it runs in a separate background thread

Solution

  1. Step 1: Understand ViewModel lifecycle

    A ViewModel is designed to be tied to the lifecycle of an activity or fragment but survives configuration changes like rotations.
  2. Step 2: Why it survives configuration changes

    When a configuration change happens, the activity is destroyed and recreated, but the ViewModel instance is retained and reused.
  3. Final Answer:

    Because it is tied to the lifecycle of the activity or fragment and not recreated on configuration changes -> Option A
  4. Quick Check:

    ViewModel lifecycle = survives config changes [OK]
Hint: ViewModel survives because it outlives activity recreation [OK]
Common Mistakes:
  • Thinking ViewModel saves data to disk automatically
  • Confusing ViewModel with static variables
  • Assuming ViewModel runs on a background thread
2. Which of the following is the correct way to get a ViewModel instance in an Activity using Kotlin?
easy
A. val model = ViewModelProvider.get(this, MyViewModel::class.java)
B. val model = MyViewModel()
C. val model = ViewModelProvider(this).get(MyViewModel::class.java)
D. val model = ViewModel()

Solution

  1. Step 1: Identify correct ViewModelProvider usage

    The correct syntax to get a ViewModel instance is using ViewModelProvider with the activity or fragment as owner.
  2. Step 2: Check Kotlin syntax

    Using ViewModelProvider(this).get(MyViewModel::class.java) is the standard way to get the ViewModel instance.
  3. Final Answer:

    val model = ViewModelProvider(this).get(MyViewModel::class.java) -> Option C
  4. Quick Check:

    ViewModelProvider(this).get() = correct syntax [OK]
Hint: Use ViewModelProvider(this).get() to get ViewModel [OK]
Common Mistakes:
  • Instantiating ViewModel directly with constructor
  • Using incorrect ViewModelProvider syntax
  • Confusing ViewModel class with instance
3. Given this code snippet in an Activity, what will be the output after a screen rotation?
class MyViewModel : ViewModel() {
  var counter = 0
}

// In Activity
val model = ViewModelProvider(this).get(MyViewModel::class.java)
model.counter += 1
println(model.counter)
medium
A. 1 on first launch, then resets to 0 after rotation
B. 1 on first launch, then increments to 2 after rotation
C. Always prints 0
D. Throws an error on rotation

Solution

  1. Step 1: Understand ViewModel data retention

    The ViewModel instance survives configuration changes, so its data like counter is preserved.
  2. Step 2: Trace counter increment

    On first launch, counter is 0, incremented to 1 and printed. After rotation, the same ViewModel instance is used, counter is 1, incremented to 2 and printed.
  3. Final Answer:

    1 on first launch, then increments to 2 after rotation -> Option B
  4. Quick Check:

    ViewModel retains data = increments preserved [OK]
Hint: ViewModel keeps data, so counter increments across rotations [OK]
Common Mistakes:
  • Assuming ViewModel resets on rotation
  • Thinking counter always starts at 0
  • Expecting an error due to rotation
4. What is wrong with this code that tries to use ViewModel in an Activity?
class MyViewModel : ViewModel() {
  var data = "Hello"
}

// In Activity
val model = MyViewModel()
println(model.data)
medium
A. The println statement is incorrect
B. The data variable must be private
C. ViewModel cannot have variables
D. ViewModel should not be instantiated directly; use ViewModelProvider instead

Solution

  1. Step 1: Identify ViewModel instantiation error

    ViewModel must be obtained via ViewModelProvider to survive configuration changes, not created with constructor.
  2. Step 2: Explain consequence

    Direct instantiation means a new ViewModel is created every time, losing data on rotation.
  3. Final Answer:

    ViewModel should not be instantiated directly; use ViewModelProvider instead -> Option D
  4. Quick Check:

    Use ViewModelProvider, not constructor [OK]
Hint: Never instantiate ViewModel with constructor directly [OK]
Common Mistakes:
  • Creating ViewModel with constructor
  • Thinking private variables fix lifecycle issues
  • Blaming println for errors
5. You want to keep user input data safe during screen rotations in your app. Which approach best uses ViewModel to achieve this?
hard
A. Store user input in a ViewModel property and update it on every input change
B. Save user input in SharedPreferences and reload after rotation
C. Use static variables in the Activity to hold user input
D. Recreate the ViewModel on each rotation and reset user input

Solution

  1. Step 1: Identify best practice for preserving UI data

    ViewModel is designed to hold UI-related data that survives configuration changes like rotations.
  2. Step 2: Choose correct data handling method

    Storing user input in a ViewModel property and updating it on input changes keeps data safe and avoids unnecessary disk operations.
  3. Final Answer:

    Store user input in a ViewModel property and update it on every input change -> Option A
  4. Quick Check:

    ViewModel holds UI data safely across rotations [OK]
Hint: Keep UI data in ViewModel properties updated live [OK]
Common Mistakes:
  • Using SharedPreferences for temporary UI data
  • Using static variables which can cause leaks
  • Recreating ViewModel loses data
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard