0
0
Android Kotlinmobile~3 mins

Why State in ViewModel in Android Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could remember everything perfectly, even when you rotate your phone?

The Scenario

Imagine you are building an app where users fill out a form. Without a ViewModel, every time the screen rotates or the app goes to the background, all the data the user entered disappears. You have to start over, which is frustrating.

The Problem

Manually saving and restoring data on every screen change or rotation is slow and error-prone. You might forget to save some fields or restore them incorrectly. This leads to bugs and a bad user experience.

The Solution

Using State in ViewModel keeps your app data safe and alive even when the screen rotates or the app pauses. The ViewModel holds the state separately from the UI, so your data stays intact and your app feels smooth and reliable.

Before vs After
Before
override fun onSaveInstanceState(outState: Bundle) {
  outState.putString("name", nameInput.text.toString())
}

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
  nameInput.setText(savedInstanceState.getString("name"))
}
After
class MyViewModel : ViewModel() {
  val name = MutableLiveData<String>()
}

// UI observes name and updates automatically
What It Enables

It enables your app to keep user data safe and consistent across configuration changes without complicated manual code.

Real Life Example

Think of a shopping app where you add items to your cart. With State in ViewModel, your cart stays the same even if you rotate your phone or switch apps, so you never lose your selections.

Key Takeaways

Manual data saving on UI changes is slow and error-prone.

ViewModel holds state separately from UI, preserving data.

This leads to smoother, more reliable apps that keep user data safe.