Step #2: Getting and Using Our Repository

Ideally, an activity or fragment does not work directly with a repository. Instead, the ViewModel works with the repository, and the activity or fragment work with the ViewModel. The big benefit that we get from a ViewModel is that it is stable across configuration changes, so data that we have retrieved from the repository is not lost when the user rotates the screen and our activity/fragments are destroyed and recreated. Right now, that is not a big benefit, since our model objects are just held in memory. If it took network I/O to get those model objects, though… now caching that data becomes a lot more important. So, we will be switching to having the repository be something the ViewModel talks to.

That implies that RosterMotor will need access to the repository, and that RosterMotor will need to expose an API that our RosterListFragment can use in lieu of the fragment working directly with the repository.

Revise RosterMotor to look like this:

package com.commonsware.todo

import androidx.lifecycle.ViewModel

class RosterMotor(private val repo: ToDoRepository) : ViewModel() {
  val items = repo.items
}

Here, we get our ToDoRepository via the constructor. In our next step, Koin will be supplying our RosterMotor, and Koin will be able to give the motor its repository. We also expose the list of items, right now just by having a reference to the repository’s list of items. That part will change a lot later on, as we start moving towards having the to-do items in a database, but this will do for now.


Prev Table of Contents Next

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