Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
124: The Repository Pattern in Kotlin
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
UserProfiledata class (includeusernameandemail). - Create
UserProfileRemoteDataSourceandUserProfileLocalDataSourceinterfaces. - Implement the concrete versions of these data sources (use a simple variable/map for the local store).
- Implement the
UserProfileRepositorywith two methods:getUserProfile(): UserProfile: Returns the cached profile if it exists; otherwise, fetches from remote, saves it, and returns it.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!
There are no comments for now.