A ViewModel keeps your app data safe when the screen changes, like rotating your phone. It helps avoid losing information and keeps the app smooth.
Why ViewModel survives configuration changes in Android Kotlin
class MyViewModel : ViewModel() { // Your data and logic here } // In your Activity or Fragment val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
The ViewModel class is part of Android Jetpack libraries.
Use ViewModelProvider to get the ViewModel instance tied to the UI controller lifecycle.
class CounterViewModel : ViewModel() { var count = 0 }
val viewModel = ViewModelProvider(this).get(CounterViewModel::class.java) viewModel.count += 1
This app shows a number and a button. When you tap the button, the number goes up. If you rotate the phone, the number stays the same because the ViewModel keeps the count safe.
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class CounterViewModel : ViewModel() { var count = 0 } class MainActivity : AppCompatActivity() { private lateinit var viewModel: CounterViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider(this).get(CounterViewModel::class.java) val textView = TextView(this).apply { text = "Count: ${viewModel.count}" textSize = 24f id = 1 } val button = Button(this).apply { text = "Increase Count" setOnClickListener { viewModel.count += 1 textView.text = "Count: ${viewModel.count}" } } val layout = android.widget.LinearLayout(this).apply { orientation = android.widget.LinearLayout.VERTICAL addView(textView) addView(button) } setContentView(layout) } }
ViewModel objects survive configuration changes like screen rotation but are cleared when the Activity or Fragment is finished.
Do not store UI elements or Context in ViewModel to avoid memory leaks.
ViewModel helps keep your app fast and user-friendly by saving data across changes.
ViewModel keeps data safe during screen rotations and other configuration changes.
It separates UI code from data logic for cleaner apps.
Use ViewModelProvider to get your ViewModel instance tied to your UI lifecycle.