-
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
197: Practice Exercise: Implementing the Repository Pattern with Coroutines
Why bother with a repository if I already have an API service and a DAO?
I get this question a lot. When you're first starting, it feels like you're just adding a "middleman" layer that doesn't actually do anything except call another function. But here's the thing: your ViewModel shouldn't care where the data comes from. It shouldn't know if you're using Retrofit for network calls or Room for a local database.
Imagine you decide to switch your local storage from Room to Realm, or you change your API from REST to GraphQL. If your ViewModel calls the DAO directly, you're hunting through your UI logic to fix data plumbing. By using a Repository, the ViewModel just asks for getUser(id), and the Repository handles the "how." It becomes the single source of truth for your data logic.
Where should I actually put the withContext(Dispatchers.IO) call?
This is a common point of friction. You'll see some people putting the dispatcher in the ViewModel and some putting it in the Repository. In my experience, the best approach is to make your Repository functions "main-safe." This means a developer should be able to call any function in your repository from the Main thread without freezing the UI.
I always put the withContext inside the Repository (or even further down in the data source). This keeps the threading concerns encapsulated. Here is how I usually structure it:
class UserRepository(
private val apiService: UserApiService,
private val userDao: UserDao
) {
suspend fun refreshUser(userId: String): User {
return withContext(Dispatchers.IO) {
// We are now on a background thread
val user = apiService.fetchUser(userId)
userDao.insertUser(user)
user
}
}
}
Now your ViewModel can just call repository.refreshUser(id) inside a viewModelScope.launch without needing to worry about which dispatcher to use.
How do I handle the "network-first, then cache" logic without it getting messy?
This is where the Repository pattern actually earns its keep. Instead of putting if/else blocks all over your UI code to check if the network is down, you wrap that orchestration inside a suspend function. I like to use a pattern where I try the network, and if it fails, I fall back to the local database.
Check out this implementation for a user profile:
suspend fun getUserProfile(userId: String): User {
return withContext(Dispatchers.IO) {
try {
// Try to get the freshest data from the web
val remoteUser = apiService.fetchUser(userId)
userDao.insertUser(remoteUser) // Update cache
remoteUser
} catch (e: Exception) {
// Network failed? Grab whatever we have in the DB
userDao.getUserById(userId)
?: throw Exception("No cached data available and network is down")
}
}
}
By doing this, the ViewModel stays clean. It just observes the result and updates the UI, regardless of whether the data came from a server in Virginia or a SQLite file on the device.
📋 Practical Task
Build a Synchronized Product Catalog Repository
Your task is to implement a ProductRepository that manages a list of products. You are provided with a ProductApiService (for remote calls) and a ProductDao (for local storage). Both of these interfaces have suspend functions.
Implement the following requirements in your ProductRepository class:
- Create a function
getProducts()that is "main-safe" (uses the correct dispatcher). - Inside
getProducts(), attempt to fetch the product list from theProductApiService. - If the network call is successful, save the list to the
ProductDaoand return the list. - If the network call fails (throws an exception), catch the error and return the list from the
ProductDao. - If the local database is also empty, throw a custom
NoDataException.
Provided Interfaces:
interface ProductApiService {
suspend fun fetchAllProducts(): List<Product>
}
interface ProductDao {
suspend fun getAllProducts(): List<Product>
suspend fun clearAndInsertProducts(products: List<Product>)
}
data class Product(val id: Int, val name: String, val price: Double)
class NoDataException : Exception("No data available")There are no comments for now.