Step #3: Saving the Change

Now, we need to update our repository, given that the user toggled the completed state of the model.

To that end, add a save() function to ToDoRepository:

  fun save(model: ToDoModel) {
    items = if (items.any { it.id == model.id }) {
      items.map { if (it.id == model.id) model else it }
    } else {
      items + model
    }
  }

Here, we see if the items list already contains the supplied model, based on the id values. If it does, this means we are replacing an existing ToDoModel with an updated copy, so we generate a new list of models, replacing the old one with the new one via map(). If, however, the list does not contain a model with this id, then we must be adding some new model to the list, so we just create a list that adds the new model to the end.

Next, add a similar save() function to RosterMotor:

  fun save(model: ToDoModel) {
    repo.save(model)
  }

Right now, all this does is call through to save() on the repository. Later, when we have to start taking database I/O and threading into account, save() will do more work. But, for now, this is all that we need.

Then, we can call save() on RosterMotor from our onCheckedChange lambda expression, over in RosterListFragment:

    val adapter = RosterAdapter(layoutInflater) {
      motor.save(it.copy(isCompleted = !it.isCompleted))
    }

Here, we create the updated model by using copy(), a function added to all Kotlin data classes. As the name suggests, copy() makes a copy of the immutable object, except it replaces whatever properties we include as parameters to the copy() call. In our case, we replace isCompleted with the opposite of its current value.

If you run this revised sample… nothing much seems to change, except that our TODO() crash is gone. You cannot readily see the objects in the repository, to see what the ToDoModel objects look like. Plus, we are only affecting memory, so these changes go away when the app’s process does. All of those limitations will be addressed in upcoming tutorials.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.