Setting Up a Repository

So, now we have a ToDoModel. Wonderful!

But, this raises the question: where do ToDoModel instances come from?

In the long term, we will be storing our to-do items in a database. For the moment, to get our UI going, we can just cache them in memory. We could, if desired, have a server somewhere that is the “system of record” for our to-do items, with the local database serving as a persistent cache.

Ideally, our UI code does not have to care about any of that. And, ideally, our code that does have to deal with all of the storage work does not care about how our UI is written.

One pattern for enforcing that sort of separation is to use a repository. The repository handles all of the data storage and retrieval work. Exactly how it does that is up to the repository itself. It offers a fairly generic API that does not “get into the weeds” of the particular storage techniques that it uses. The UI layer works with the repository to get data, create new data, update or delete existing data, and so on, and the repository does the actual work.

So, in this tutorial, we will set up a simple repository. Right now, that will just be an in-memory cache, but in later tutorials we will move that data to a database.

This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.

Step #1: Adding the Repository Class

Once again, we need another Kotlin class.

Right-click over the com.commonsware.todo package in the project tree in Android Studio, and choose “New” > “Kotlin File/Class” from the context menu. As before, this brings up a dialog where we can define a new Kotlin source file, by default into the same Java package that we right-clicked over. Fill in ToDoRepository in the “Name” field, and choose “Class” from the list of Kotlin structures. Then press Enter or Return to create this file. ToDoRepository should show up in an editor, with an implementation like this:

package com.commonsware.todo

class ToDoRepository {
}

Prev Table of Contents Next

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