CPS251 Android Development by Scott Shaper

Building the Repository

The Repository pattern is a design pattern used to abstract the way data is accessed. In Android development, especially with Room, a Repository acts as a clean API for your UI or ViewModel to interact with different data sources (like a database, network, or device storage). It centralizes data operations, making your code modular, testable, and easier to maintain.

Think of the Repository as a librarian. Instead of your ViewModel (the student) directly going to the database (the shelves) to find or store books, the ViewModel asks the librarian (Repository) for what it needs. The librarian knows where the books are, how to get them, and how to put them back, without the student needing to know the details of the library's internal organization.

Why Use a Repository?

Example: NoteRepository (from RoomDatabaseDemo)


// NoteRepository acts as an abstraction layer over the data source (NoteDao).
// It provides a clean API for the ViewModel to interact with data.
class NoteRepository(private val noteDao: NoteDao) {
    // Exposes a Flow of all notes, allowing for observing changes in the database.
    val allNotes: Flow<List<Note>> = noteDao.getAllNotes()

    // Suspended function to insert a new note into the database.
    // Marked as suspend because Room operations are asynchronous.
    suspend fun insert(note: Note) = noteDao.insert(note)

    // Suspended function to delete an existing note from the database.
    // Marked as suspend because Room operations are asynchronous.
    suspend fun delete(note: Note) = noteDao.delete(note)
} 
        

Understanding the `NoteRepository` Class

The NoteRepository class is designed to encapsulate the logic for accessing data from a single source, in our case, the NoteDao. It provides a clean API for the ViewModel, abstracting the details of database operations.

1. Class Definition and Dependency Injection


class NoteRepository(private val noteDao: NoteDao) {
    // ...
}

2. Exposing All Notes as a Flow


    val allNotes: Flow<List<Note>> = noteDao.getAllNotes()

3. Inserting a Note


    suspend fun insert(note: Note) = noteDao.insert(note)

4. Deleting a Note


    suspend fun delete(note: Note) = noteDao.delete(note)

Tips for Success

Common Mistakes to Avoid

Best Practices