Skip to Content
Course content

124: The Repository Pattern in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've likely felt the pain of "leaky abstractions." It usually starts when you call a network library directly from your UI code. Everything works great until you decide to add a local cache, or you realize your unit tests are trying to make real HTTP requests. That's where the Repository pattern comes in. Think of it as a mediator: the rest of your app asks the Repository for data, and the Repository decides whether to grab it from the cloud, a local database, or a memory cache.

Let's build a simple book-tracking feature. We want to fetch a list of books, but we want the app to feel snappy, so we'll implement a basic caching strategy.

Defining the Book domain

First, we need a clear idea of what a "Book" is. I always recommend keeping your domain models separate from your API models. If the API changes a field name from book_title to title, you don't want that change ripple-effecting through your entire UI layer.

data class Book(
    val id: String,
    val title: String,
    val author: String
)

Creating the data sources

I like to split my data logic into "Data Sources." One handles the remote API, and one handles the local storage. In a real app, the local source would be a Room database, but for this example, we'll use a simple MutableMap to keep things concise.

class RemoteBookDataSource {
    // Simulating a network call
    suspend fun fetchBooks(): List<Book> {
        println("Fetching from network...")
        return listOf(
            Book("1", "The Kotlin Guide", "Jane Doe"),
            Book("2", "Clean Code", "Robert C. Martin")
        )
    }
}

class LocalBookDataSource {
    private val cache = mutableMapOf<String, Book>()

    fun getBooks(): List<Book> = cache.values.toList()

    fun saveBooks(books: List<Book>) {
        books.forEach { cache[it.id] = it }
    }
}

The initial (and flawed) Repository

Now, I'll wire these together. My goal is to check the local cache first; if it's empty, I'll hit the network and save the result locally.

class BookRepository(
    private val remoteDataSource: RemoteBookDataSource,
    private val localDataSource: LocalBookDataSource
) {
    suspend fun getBooks(): List<Book> {
        val localBooks = localDataSource.getBooks()
        return if (localBooks.isNotEmpty()) {
            localBooks
        } else {
            val remoteBooks = remoteDataSource.fetchBooks()
            localDataSource.saveBooks(remoteBooks)
            remoteBooks
        }
    }
}

Wait, I've made a mistake

I just realized I've fallen into a common trap. By passing the concrete RemoteBookDataSource and LocalBookDataSource classes directly into the constructor, I've tightly coupled my repository to these specific implementations. If I want to write a unit test for BookRepository, I'm forced to use the real data sources, which means my tests are now slow and dependent on a "fake" network.

I need to abstract these behind interfaces. This is a small step that saves hours of frustration during testing.

interface BookRemoteDataSource {
    suspend fun fetchBooks(): List<Book>
}

interface BookLocalDataSource {
    fun getBooks(): List<Book>
    fun saveBooks(books: List<Book>)
}

// Now the Repository depends on the interfaces, not the classes
class BookRepository(
    private val remoteDataSource: BookRemoteDataSource,
    private val localDataSource: BookLocalDataSource
) {
    suspend fun getBooks(): List<Book> {
        val localBooks = localDataSource.getBooks()
        return if (localBooks.isNotEmpty()) {
            localBooks
        } else {
            val remoteBooks = remoteDataSource.fetchBooks()
            localDataSource.saveBooks(remoteBooks)
            remoteBooks
        }
    }
}

Refining the logic for a "Single Source of Truth"

To wrap this up, I want to ensure that the local cache is always the "Single Source of Truth." Instead of returning the remote list directly, the repository should save the remote data to the local source and then return whatever is in the local source. This ensures that the UI always sees the data exactly as it exists in the database.

class BookRepository(
    private val remoteDataSource: BookRemoteDataSource,
    private val localDataSource: BookLocalDataSource
) {
    suspend fun getBooks(): List<Book> {
        val localBooks = localDataSource.getBooks()
        
        if (localBooks.isEmpty()) {
            val remoteBooks = remoteDataSource.fetchBooks()
            localDataSource.saveBooks(remoteBooks)
        }
        
        // Always return from local source
        return localDataSource.getBooks()
    }
}

Now, the UI doesn't know (or care) where the books came from. It just knows that the BookRepository provides them. If we decide to switch from a Map to a SQL database, or from a REST API to GraphQL, we only change the data source implementations. The repository logic and the UI stay exactly the same.




📋 Practical Task

Build a UserProfile Repository with Refresh Logic

Your task is to implement a UserProfileRepository following the patterns we just discussed. You need to handle a user profile that can be refreshed manually.

Requirements:

  • Create a UserProfile data class (include username and email).
  • Create UserProfileRemoteDataSource and UserProfileLocalDataSource interfaces.
  • Implement the concrete versions of these data sources (use a simple variable/map for the local store).
  • Implement the UserProfileRepository with two methods:
    1. getUserProfile(): UserProfile: Returns the cached profile if it exists; otherwise, fetches from remote, saves it, and returns it.
    2. refreshUserProfile(): UserProfile: Forces a network fetch regardless of the cache, updates the cache, and returns the new profile.

Make sure your repository depends on the interfaces, not the concrete implementations!

Rating
0 0

There are no comments for now.

to be the first to leave a comment.