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

Take your career further with a Pro subscription. 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.

Challenge: Create a ViewModel Pro

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:


Put your new MVVM skills to work by creating a ViewModel for the All Creatures screen that shows a list of all creatures in the repository.


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

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a Professional subscription.

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()