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

Next
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:

binding.avatarListItem.setImageDrawable(
    AppCompatResources.getDrawable(
        binding.avatarListItem.context,
        creature.drawable
    )
)

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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(AllCreaturesViewModel::class.java)
    viewModel.getAllCreaturesLiveData().observe(this, Observer { creatures ->
      creatures?.let {
        adapter.updateCreatures(creatures)
      }
    })
viewModel.clearAllCreatures()
  itemView.avatarListItem.setImageDrawable(itemView.context.getDrawable(creature.drawable))
itemView.name.text = creature.name
itemView.hitPoints.text = creature.hitPoints.toString()