0
0
Android Kotlinmobile~3 mins

Why ViewModel survives configuration changes in Android Kotlin - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your app could keep data safe even when the screen flips without extra code?

The Scenario

Imagine you are building an Android app that shows user data. When the phone rotates, the screen reloads and all your data disappears. You have to reload everything again, making the app slow and frustrating.

The Problem

Manually saving and restoring data on every screen rotation is tricky and error-prone. You might forget to save some data or reload it incorrectly. This leads to bugs and a poor user experience.

The Solution

The ViewModel keeps your data safe even when the screen rotates. It lives separately from the screen and survives configuration changes, so your data stays intact without extra work.

Before vs After
Before
override fun onSaveInstanceState(outState: Bundle) {
  outState.putString("data", data)
}
override fun onCreate(savedInstanceState: Bundle?) {
  data = savedInstanceState?.getString("data") ?: loadData()
}
After
class MyViewModel : ViewModel() {
  val data = MutableLiveData<String>()
}
// Activity just observes data, no manual save/restore needed
What It Enables

With ViewModel, your app feels smooth and reliable because data stays ready even after screen rotations or other changes.

Real Life Example

Think of a news app where you scroll through articles. When you rotate your phone, the list stays exactly where you left it without reloading everything.

Key Takeaways

Manual data saving on rotation is slow and error-prone.

ViewModel keeps data alive across configuration changes automatically.

This leads to smoother apps and happier users.