Complete the code to declare a ViewModel class in Kotlin.
class MyViewModel : [1]() { // ViewModel logic here }
The ViewModel class in Android is declared by extending the ViewModel class.
Complete the code to observe LiveData from the ViewModel in an Activity.
viewModel.data.observe([1]) { value -> // update UI with value }
viewLifecycleOwner in an Activity.In an Activity, this refers to the LifecycleOwner needed to observe LiveData.
Fix the error in the ViewModel factory code to create a ViewModel with parameters.
class MyViewModelFactory(private val repo: Repository) : ViewModelProvider.[1] { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MyViewModel::class.java)) { return MyViewModel(repo) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
The correct interface to implement for a ViewModel factory is ViewModelProvider.Factory.
Fill both blanks to create a LiveData property in ViewModel and expose it as immutable LiveData.
private val _data = MutableLiveData<String>() val data: LiveData<String> = _data[1][2]
To expose immutable LiveData, just assign the MutableLiveData to LiveData without extra calls.
Fill all three blanks to update LiveData value safely from a background thread.
fun fetchData() {
viewModelScope.[1] {
val result = repository.getData()
_data.[2] = result
// or use _data.[3](result) if needed
}
}Use launch to start a coroutine, update LiveData's value on main thread, or postValue from background thread.