0
0
Android Kotlinmobile~20 mins

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

Choose your learning style9 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