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.

Save Data to the Repository Pro

The saveCreature() method’s code in the view model has been updated in the final project in the download materials. It lauches a new coroutine without blocking the current thread. It looks like this now:

fun saveCreature() = viewModelScope.launch {

The conditional check is now done in the click listener of the the save button. Check out the final project to see the changes.

Add the ability for the ViewModel to save Model data into the repository when receiving user events from the View layer.


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.

In this video, we’ll save new creatures into the repository we previously setup. We don’t want the user to be able to save creatures with blank attributes, for example, a blank name. Let’s write a view model test to make sure that creatures with blank names can’t be saved.

  fun testCantSaveCreatureWithBlankName() {
    creatureViewModel.intelligence = 10
    creatureViewModel.strength = 3
    creatureViewModel.endurance = 7
    creatureViewModel.drawable = 1 = ""
     val canSaveCreature = creatureViewModel.canSaveCreature()
     assertEquals(false, canSaveCreature)
private val repository: CreatureRepository = RoomRepository()
  lateinit var repository: CreatureRepository
creatureViewModel = CreatureViewModel(mockGenerator, repository)
   fun canSaveCreature(): Boolean {
    return intelligence != 0 && strength != 0 && endurance != 0 &&
        name.isNotEmpty() && drawable != 0
  fun saveCreature(): Boolean {
    return if (canSaveCreature()) {
    } else {

      if (viewModel.saveCreature()) {
        Toast.makeText(this, getString(R.string.creature_saved), Toast.LENGTH_SHORT).show()
      } else {
        Toast.makeText(this, getString(R.string.error_saving_creature), Toast.LENGTH_SHORT).show()