0
0
Android Kotlinmobile~10 mins

MVVM pattern in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a ViewModel class in Kotlin.

Android Kotlin
class MyViewModel : [1]() {
  // ViewModel logic here
}
Drag options to blanks, or click blank then click option'
AService
BViewModel
CFragment
DActivity
Attempts:
3 left
💡 Hint
Common Mistakes
Extending Activity or Fragment instead of ViewModel.
Forgetting to extend any class.
2fill in blank
medium

Complete the code to observe LiveData from the ViewModel in an Activity.

Android Kotlin
viewModel.data.observe([1]) { value ->
  // update UI with value
}
Drag options to blanks, or click blank then click option'
Athis
BlifecycleOwner
CviewLifecycleOwner
Dcontext
Attempts:
3 left
💡 Hint
Common Mistakes
Using viewLifecycleOwner in an Activity.
Passing null or wrong context.
3fill in blank
hard

Fix the error in the ViewModel factory code to create a ViewModel with parameters.

Android Kotlin
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")
  }
}
Drag options to blanks, or click blank then click option'
AFactory
BNewInstanceFactory
CProviderFactory
DViewModelFactory
Attempts:
3 left
💡 Hint
Common Mistakes
Extending a non-existent class.
Not overriding the create method properly.
4fill in blank
hard

Fill both blanks to create a LiveData property in ViewModel and expose it as immutable LiveData.

Android Kotlin
private val _data = MutableLiveData<String>()
val data: LiveData<String> = _data[1][2]
Drag options to blanks, or click blank then click option'
AasLiveData()
Bget()
D.value
Attempts:
3 left
💡 Hint
Common Mistakes
Calling .value or asLiveData() unnecessarily.
Trying to create a new LiveData instance.
5fill in blank
hard

Fill all three blanks to update LiveData value safely from a background thread.

Android Kotlin
fun fetchData() {
  viewModelScope.[1] {
    val result = repository.getData()
    _data.[2] = result
    // or use _data.[3](result) if needed
  }
}
Drag options to blanks, or click blank then click option'
Alaunch
BpostValue
Cvalue
Dasync
Attempts:
3 left
💡 Hint
Common Mistakes
Using async without awaiting.
Setting LiveData value from background thread directly.