0
0
Android Kotlinmobile~3 mins

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

Choose your learning style9 modes available
The Big Idea

What if your app never lost user data even when the screen flips?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
override fun onSaveInstanceState(outState: Bundle) {
  outState.putString("name", userName)
}
override fun onCreate(savedInstanceState: Bundle?) {
  userName = savedInstanceState?.getString("name") ?: ""
}
After
class UserViewModel : ViewModel() {
  val userName = MutableLiveData<String>()
}
// Activity or Fragment just observes userName without manual saving
What It Enables

With ViewModel, your app can smoothly handle screen rotations and lifecycle changes without losing data or crashing.

Real Life Example

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.

Key Takeaways

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.