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

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 {

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've reached locked video content where the transcript will be shown as obfuscated text.

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