import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
class CounterViewModel(private val state: SavedStateHandle) : ViewModel() {
companion object {
private const val COUNT_KEY = "count"
}
private val _count = MutableLiveData(state.get<Int>(COUNT_KEY) ?: 0)
val count: LiveData<Int> = _count
fun increment() {
val newCount = (_count.value ?: 0) + 1
_count.value = newCount
state.set(COUNT_KEY, newCount)
}
}
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: CounterViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this, object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(CounterViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return CounterViewModel(SavedStateHandle()) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}).get(CounterViewModel::class.java)
val countText = findViewById<TextView>(R.id.countText)
val incrementButton = findViewById<Button>(R.id.incrementButton)
viewModel.count.observe(this, Observer { count ->
countText.text = "Count: $count"
})
incrementButton.setOnClickListener {
viewModel.increment()
}
}
}We created a CounterViewModel that takes a SavedStateHandle to store the count value. The count is stored in a MutableLiveData initialized from the saved state or 0 if none exists. The increment() function updates the count and saves it back to SavedStateHandle.
In MainActivity, we initialize the ViewModel with a factory that provides a SavedStateHandle. We observe the count LiveData to update the UI text. When the '+' button is clicked, we call increment() to increase the count.
This setup ensures the count value survives configuration changes and process death because SavedStateHandle saves the state automatically.