0
0
Android Kotlinmobile~5 mins

ViewModel creation in Android Kotlin

Choose your learning style9 modes available
Introduction

A ViewModel helps keep your app data safe when the screen changes or rotates. It holds data for the screen and keeps it alive.

When you want to keep user data safe during screen rotation.
When you need to share data between different parts of the app screen.
When you want to separate data logic from the screen design.
When you want to avoid losing data after temporary app pauses.
When you want to make your app easier to test and maintain.
Syntax
Android Kotlin
class MyViewModel : ViewModel() {
    // Your data and functions here
}
ViewModel classes extend the ViewModel base class.
They do not hold references to UI elements to avoid memory leaks.
Examples
This ViewModel holds a simple counter and a function to increase it.
Android Kotlin
class CounterViewModel : ViewModel() {
    var count = 0

    fun increment() {
        count++
    }
}
This ViewModel holds a user name using LiveData to update the UI automatically.
Android Kotlin
class UserViewModel : ViewModel() {
    val userName = MutableLiveData<String>()

    fun setUserName(name: String) {
        userName.value = name
    }
}
Sample App

This ViewModel holds a message that can be shown on the screen. It starts with a greeting.

Android Kotlin
import androidx.lifecycle.ViewModel
import androidx.lifecycle.MutableLiveData

class SimpleViewModel : ViewModel() {
    val message = MutableLiveData<String>()

    init {
        message.value = "Hello from ViewModel!"
    }
}
OutputSuccess
Important Notes

ViewModels survive configuration changes like screen rotation.

Do not store UI elements or Context inside ViewModel to avoid memory leaks.

Use LiveData inside ViewModel to notify UI about data changes.

Summary

ViewModel keeps data safe during screen changes.

Create ViewModel by extending the ViewModel class.

Use LiveData inside ViewModel to update UI reactively.