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.
A ViewModel helps keep your app data safe when the screen changes or rotates. It holds data for the screen and keeps it alive.
class MyViewModel : ViewModel() { // Your data and functions here }
class CounterViewModel : ViewModel() { var count = 0 fun increment() { count++ } }
class UserViewModel : ViewModel() {
val userName = MutableLiveData<String>()
fun setUserName(name: String) {
userName.value = name
}
}This ViewModel holds a message that can be shown on the screen. It starts with a greeting.
import androidx.lifecycle.ViewModel import androidx.lifecycle.MutableLiveData class SimpleViewModel : ViewModel() { val message = MutableLiveData<String>() init { message.value = "Hello from ViewModel!" } }
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.
ViewModel keeps data safe during screen changes.
Create ViewModel by extending the ViewModel class.
Use LiveData inside ViewModel to update UI reactively.
ViewModel in Android development?counter.value is printed after increment() is called twice?
class CounterViewModel : ViewModel() {
val counter = MutableLiveData(0)
fun increment() {
counter.value = (counter.value ?: 0) + 1
}
}class SampleViewModel : ViewModel() {
val data = MutableLiveData<String>()
fun updateData(newData: String) {
data.value = newData
}
fun getData(): String {
return data.value
}
}Pass the test and this pattern moves unknown