MVVM on Android

Sep 1 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk | 2021.2.1 Patch 1

Part 1: MVVM on Android

10. Challenge: Create a ViewModel

Episode complete

Play next episode

About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 09. Challenge: Add ViewModel Test Next episode: 11. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 10. Challenge: Create a ViewModel

The clearAllCreatures() method in the AllCreaturesViewModel class uses Kotlin Coroutine and would look like this:

fun clearAllCreatures() = viewModelScope.launch { repository.clearAllCreatures() }

Also AppCompatResources is preffered over context.getDrawable() as the IDE recommends you to do this. So the code to set the avatarListItem image in the bind() method of the ViewHolder class would be:


Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Your next challenge is to put together all you’ve learned so far to build a view model for the app’s first screen that should show the list of all creatures in the repository.

class AllCreaturesViewModel(private val repository: CreatureRepository = RoomRepository()) : ViewModel() {
  private val allCreaturesLiveData = repository.getAllCreatures()

  fun getAllCreaturesLiveData() = allCreaturesLiveData
fun clearAllCreatures() = repository.clearAllCreatures()
private lateinit var viewModel: AllCreaturesViewModel
viewModel = ViewModelProviders.of(this).get(
    viewModel.getAllCreaturesLiveData().observe(this, Observer { creatures ->
      creatures?.let {
  itemView.avatarListItem.setImageDrawable(itemView.context.getDrawable(creature.drawable)) =
itemView.hitPoints.text = creature.hitPoints.toString()