MVVM on Android

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

Part 1: MVVM on Android

08. Save Data to the Repository

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: 07. Test the ViewModel Next episode: 09. Challenge: Add ViewModel Test

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: 08. Save Data to the Repository

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.

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

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