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

Take your career further with a raywenderlich.com 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 {
  repository.saveCreature(creature)
}

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.

Contributors

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 raywenderlich.com 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.

  @Test
  fun testCantSaveCreatureWithBlankName() {
    creatureViewModel.intelligence = 10
    creatureViewModel.strength = 3
    creatureViewModel.endurance = 7
    creatureViewModel.drawable = 1
    creatureViewModel.name = ""
     val canSaveCreature = creatureViewModel.canSaveCreature()
     assertEquals(false, canSaveCreature)
  }
private val repository: CreatureRepository = RoomRepository()
  @Mock
  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()) {
      repository.saveCreature(creature)
      true
    } else {
      false
    }
  }

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

Reviews

Comments