{"id":181,"date":"2026-10-19T15:50:00","date_gmt":"2026-10-19T15:50:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=181"},"modified":"2026-11-06T08:48:27","modified_gmt":"2026-11-06T08:48:27","slug":"repository-pattern-in-android-with-kotlin-jetpack-compose-single-source-of-truth-caching-offline-first","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/repository-pattern-in-android-with-kotlin-jetpack-compose-single-source-of-truth-caching-offline-first\/","title":{"rendered":"Repository Pattern in Android with Kotlin &#038; Jetpack Compose: Single Source of Truth, Caching &#038; Offline-First"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Modern Android applications frequently interact with multiple data sources.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, an e-commerce application might retrieve product information from a REST API, cache products in a local Room database, and display the latest available data using Jetpack Compose.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Managing these data sources directly inside Activities, composables, or ViewModels can quickly become complicated.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What happens when the internet connection is unavailable?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">How should the application handle cached data?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">How can the UI automatically update when the database changes?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">How do we avoid duplicate network requests?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These problems can be addressed through a well-designed <strong>Repository Pattern<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll learn how to implement repositories using Kotlin, Room, Retrofit, Coroutines, Flow, MVVM, and Jetpack Compose.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also build a practical offline-first product catalog.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What You&#8217;ll Learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What the Repository Pattern is<\/li>\n\n\n\n<li>Why repositories are important<\/li>\n\n\n\n<li>Repository interfaces and implementations<\/li>\n\n\n\n<li>Local and remote data sources<\/li>\n\n\n\n<li>Single Source of Truth<\/li>\n\n\n\n<li>Offline-first architecture<\/li>\n\n\n\n<li>Room database integration<\/li>\n\n\n\n<li>Retrofit API integration<\/li>\n\n\n\n<li>Kotlin Flow and reactive data<\/li>\n\n\n\n<li>Data caching strategies<\/li>\n\n\n\n<li>Cache invalidation<\/li>\n\n\n\n<li>Synchronization and error handling<\/li>\n\n\n\n<li>MVVM integration<\/li>\n\n\n\n<li>Jetpack Compose integration<\/li>\n\n\n\n<li>Repository testing<\/li>\n\n\n\n<li>Production best practices<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. What Is the Repository Pattern?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The Repository Pattern provides a consistent interface for accessing application data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of allowing ViewModels to communicate directly with Retrofit services or Room DAOs, a repository coordinates those operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Without Repository Pattern<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>ProductViewModel\n    |\n    +---- Retrofit API\n    |\n    +---- Room DAO\n    |\n    +---- Cache Logic\n    |\n    +---- Error Handling<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">With Repository Pattern<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>ProductViewModel\n       |\n       v\nProductRepository\n       |\n       +---- Retrofit API\n       |\n       +---- Room Database\n       |\n       +---- Synchronization<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel requests data through the repository.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The repository decides how to obtain and manage that data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Separation of concerns<\/li>\n\n\n\n<li>Easier unit testing<\/li>\n\n\n\n<li>Centralized data management<\/li>\n\n\n\n<li>Reduced coupling<\/li>\n\n\n\n<li>Offline support<\/li>\n\n\n\n<li>Better maintainability<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Repository Pattern in MVVM Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The Repository Pattern fits naturally into MVVM.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|      Jetpack Compose UI        |\n+--------------------------------+\n               |\n               | User Actions\n               v\n+--------------------------------+\n|        ProductViewModel        |\n|        StateFlow UI State      |\n+--------------------------------+\n               |\n               v\n+--------------------------------+\n|       ProductRepository        |\n+--------------------------------+\n          |           |\n          v           v\n    Retrofit API   Room Database<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Responsibilities<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Jetpack Compose<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Displays UI and forwards user interactions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>ViewModel<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Manages UI state and coordinates loading or refresh operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Repository<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Provides application data and coordinates its sources.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Remote Data Source<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Communicates with network APIs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Local Data Source<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Stores and retrieves cached data.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Repository Interfaces vs Implementations<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A repository interface defines the operations available to consumers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Interface<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>interface ProductRepository {\n\n    fun observeProducts(): Flow&lt;List&lt;Product&gt;&gt;\n\n    suspend fun refreshProducts()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Implementation<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductRepositoryImpl(\n    private val api: ProductApi,\n    private val dao: ProductDao\n) : ProductRepository {\n\n    override fun observeProducts(): Flow&lt;List&lt;Product&gt;&gt; {\n        return dao.observeProducts()\n            .map { entities -&gt;\n                entities.map { it.toDomain() }\n            }\n    }\n\n    override suspend fun refreshProducts() {\n        \/\/ Fetch, validate, and cache remote products.\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The interface describes what the repository provides.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The implementation determines how the operations work.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use repository interfaces when they improve dependency boundaries, testing, or implementation flexibility.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A separate interface is not mandatory for every small application.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. What Is a Single Source of Truth?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A Single Source of Truth (SSOT) is the authoritative source from which application state is read.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In many offline-first Android applications, the local Room database serves as the source of truth.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Architecture<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\"> <code>       Remote API\n            |\n            | Fetch\n            v\n      ProductRepository\n            |\n            | Save\n            v\n       Room Database\n            |\n            | Flow\n            v\n      ProductViewModel\n            |\n            | StateFlow\n            v\n       Jetpack Compose<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI does not display separate network and database product lists.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>The repository retrieves remote data.<\/li>\n\n\n\n<li>Remote data is validated and stored in Room.<\/li>\n\n\n\n<li>Room emits updated records.<\/li>\n\n\n\n<li>ViewModel observes the database Flow.<\/li>\n\n\n\n<li>Jetpack Compose displays the latest local data.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Consistent UI state<\/li>\n\n\n\n<li>Offline access<\/li>\n\n\n\n<li>Fewer conflicting data sources<\/li>\n\n\n\n<li>Reactive updates<\/li>\n\n\n\n<li>Simpler data flow<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Single Source of Truth does not mean an application can only have one data source.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It means the application has a clearly defined authoritative source for a particular kind of data.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. What Is Offline-First Architecture?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Offline-first architecture prioritizes useful application behavior even when network connectivity is unavailable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a product catalog can display previously downloaded products while the user is offline.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Offline-First Flow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Application Starts\n        |\n        v\nRead Local Database\n        |\n        v\nDisplay Cached Products\n        |\n        v\nAttempt Network Refresh\n        |\n   +----+----+\n   |         |\nSuccess    Failure\n   |         |\n   v         v\nUpdate DB  Keep Cache\n   |\n   v\nUI Updates Automatically<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Faster initial data display<\/li>\n\n\n\n<li>Better experience on unstable networks<\/li>\n\n\n\n<li>Reduced dependence on continuous connectivity<\/li>\n\n\n\n<li>Improved reliability<\/li>\n\n\n\n<li>Consistent reactive UI<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Offline-first does not automatically mean every feature works offline.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Actions such as payments, authentication, or server-authoritative transactions may still require network connectivity.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Understanding Data Sources<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A data source is responsible for communicating with a particular storage or networking system.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Remote Data Source<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>interface ProductRemoteDataSource {\n\n    suspend fun getProducts(): List&lt;ProductDto&gt;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Local Data Source<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>interface ProductLocalDataSource {\n\n    fun observeProducts(): Flow&lt;List&lt;ProductEntity&gt;&gt;\n\n    suspend fun saveProducts(\n        products: List&lt;ProductEntity&gt;\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Remote data sources handle network access.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Local data sources handle database or file operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Introduce dedicated data-source abstractions when they simplify complex integrations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For small applications, repositories may directly use Retrofit services and Room DAOs.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. Understanding Data Transfer Objects<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A Data Transfer Object (DTO) represents data received from or sent to an external service.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Serializable\ndata class ProductDto(\n    val id: Int,\n    val title: String,\n    val price: Double,\n    val category: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The DTO represents the API response.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The remote API determines its field structure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The rest of the application should not necessarily depend directly on that structure.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Understanding Room Entities<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Room entities represent database tables.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Entity(tableName = \"products\")\ndata class ProductEntity(\n\n    @PrimaryKey\n    val id: Int,\n\n    val name: String,\n\n    val price: Double,\n\n    val category: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Room uses the entity to create and manage the products table.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Database entities and remote DTOs serve different purposes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Separate them when their schemas or responsibilities differ.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Mapping DTOs to Database Entities<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Data mapping converts one representation into another.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun ProductDto.toEntity(): ProductEntity {\n\n    return ProductEntity(\n        id = id,\n        name = title,\n        price = price,\n        category = category\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The API uses the field title.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The database uses the field name.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The mapper handles the difference.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Clear boundaries<\/li>\n\n\n\n<li>Flexible API changes<\/li>\n\n\n\n<li>Easier testing<\/li>\n\n\n\n<li>Better maintainability<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">Practical Mini-Project: Offline-First Product Catalog<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s implement a product catalog that supports cached data and network synchronization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Fetch products from a REST API<\/li>\n\n\n\n<li>Store products in Room<\/li>\n\n\n\n<li>Display cached products offline<\/li>\n\n\n\n<li>Observe database updates using Flow<\/li>\n\n\n\n<li>Refresh products manually<\/li>\n\n\n\n<li>Show synchronization errors<\/li>\n\n\n\n<li>Keep cached data after network failure<\/li>\n\n\n\n<li>Use MVVM and Jetpack Compose<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Technology Stack<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Kotlin<\/li>\n\n\n\n<li>Jetpack Compose<\/li>\n\n\n\n<li>Material 3<\/li>\n\n\n\n<li>Room<\/li>\n\n\n\n<li>Retrofit<\/li>\n\n\n\n<li>Kotlin Serialization<\/li>\n\n\n\n<li>Coroutines<\/li>\n\n\n\n<li>Flow<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>ViewModel<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For demonstration, we&#8217;ll use a sample product API. The response format must match the selected API endpoint.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Recommended Project Structure<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>com.example.offlineproducts\/\n\u2502\n\u251c\u2500\u2500 data\/\n\u2502   \u251c\u2500\u2500 local\/\n\u2502   \u2502   \u251c\u2500\u2500 ProductEntity.kt\n\u2502   \u2502   \u251c\u2500\u2500 ProductDao.kt\n\u2502   \u2502   \u2514\u2500\u2500 AppDatabase.kt\n\u2502   \u2502\n\u2502   \u251c\u2500\u2500 remote\/\n\u2502   \u2502   \u251c\u2500\u2500 ProductDto.kt\n\u2502   \u2502   \u251c\u2500\u2500 ProductResponse.kt\n\u2502   \u2502   \u2514\u2500\u2500 ProductApi.kt\n\u2502   \u2502\n\u2502   \u251c\u2500\u2500 mapper\/\n\u2502   \u2502   \u2514\u2500\u2500 ProductMapper.kt\n\u2502   \u2502\n\u2502   \u2514\u2500\u2500 repository\/\n\u2502       \u2514\u2500\u2500 ProductRepositoryImpl.kt\n\u2502\n\u251c\u2500\u2500 domain\/\n\u2502   \u251c\u2500\u2500 model\/\n\u2502   \u2502   \u2514\u2500\u2500 Product.kt\n\u2502   \u2502\n\u2502   \u2514\u2500\u2500 repository\/\n\u2502       \u2514\u2500\u2500 ProductRepository.kt\n\u2502\n\u251c\u2500\u2500 presentation\/\n\u2502   \u2514\u2500\u2500 products\/\n\u2502       \u251c\u2500\u2500 ProductUiState.kt\n\u2502       \u251c\u2500\u2500 ProductViewModel.kt\n\u2502       \u2514\u2500\u2500 ProductScreen.kt\n\u2502\n\u2514\u2500\u2500 MainActivity.kt<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is a single-module project organized into logical packages.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Add Required Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create an Empty Activity project with Jetpack Compose enabled.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In your app-level Gradle configuration, add the required dependencies.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    \/\/ Room\n    implementation(libs.androidx.room.runtime)\n    implementation(libs.androidx.room.ktx)\n    ksp(libs.androidx.room.compiler)\n\n    \/\/ Retrofit\n    implementation(libs.retrofit)\n    implementation(libs.retrofit.kotlinx.serialization)\n\n    \/\/ Kotlin Serialization\n    implementation(libs.kotlinx.serialization.json)\n\n    \/\/ Coroutines\n    implementation(libs.kotlinx.coroutines.android)\n\n    \/\/ ViewModel\n    implementation(libs.androidx.lifecycle.viewmodel.ktx)\n    implementation(libs.androidx.lifecycle.viewmodel.compose)\n\n    \/\/ Lifecycle-aware Compose\n    implementation(libs.androidx.lifecycle.runtime.compose)\n\n    \/\/ Jetpack Compose\n    implementation(libs.androidx.compose.material3)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These are illustrative version-catalog aliases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Configure matching entries in <code>gradle\/libs.versions.toml<\/code>, use compatible stable library versions, and apply the Kotlin Serialization and KSP plugins.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For Retrofit, use a converter compatible with kotlinx.serialization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Internet Permission<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add the following permission to AndroidManifest.xml:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;uses-permission android:name=\"android.permission.INTERNET\" \/&gt;<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Create the Domain Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>domain\/model\/Product.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.domain.model\n\ndata class Product(\n    val id: Int,\n    val name: String,\n    val price: Double,\n    val category: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This class represents the product used by application logic and presentation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not depend on Retrofit or Room.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Create the Room Entity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/local\/ProductEntity.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.local\n\nimport androidx.room.Entity\nimport androidx.room.PrimaryKey\n\n@Entity(tableName = \"products\")\ndata class ProductEntity(\n\n    @PrimaryKey\n    val id: Int,\n\n    val name: String,\n\n    val price: Double,\n\n    val category: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each ProductEntity corresponds to a row in the products table.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Create the Product DAO<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/local\/ProductDao.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.local\n\nimport androidx.room.Dao\nimport androidx.room.Insert\nimport androidx.room.OnConflictStrategy\nimport androidx.room.Query\nimport androidx.room.Transaction\nimport kotlinx.coroutines.flow.Flow\n\n@Dao\ninterface ProductDao {\n\n    @Query(\"SELECT * FROM products ORDER BY name ASC\")\n    fun observeProducts(): Flow&lt;List&lt;ProductEntity&gt;&gt;\n\n    @Insert(onConflict = OnConflictStrategy.REPLACE)\n    suspend fun insertProducts(\n        products: List&lt;ProductEntity&gt;\n    )\n\n    @Query(\"DELETE FROM products\")\n    suspend fun deleteAllProducts()\n\n    @Transaction\n    suspend fun replaceProducts(\n        products: List&lt;ProductEntity&gt;\n    ) {\n        deleteAllProducts()\n        insertProducts(products)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">observeProducts() returns a Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Whenever the products table changes, Room can emit an updated result.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">replaceProducts() performs deletion and insertion within a transaction.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This example assumes the API returns the complete product collection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For paginated or partial responses, do not replace the entire table with a partial result.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Create the Room Database<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/local\/AppDatabase.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.local\n\nimport androidx.room.Database\nimport androidx.room.RoomDatabase\n\n@Database(\n    entities = &#91;ProductEntity::class],\n    version = 1,\n    exportSchema = true\n)\nabstract class AppDatabase : RoomDatabase() {\n\n    abstract fun productDao(): ProductDao\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">AppDatabase provides access to ProductDao.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In production, configure Room schema export and database migrations as your schema evolves.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Create the Remote DTO<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For this tutorial, we&#8217;ll use the DummyJSON products API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example endpoint:<\/p>\n\n\n\n<figure class=\"wp-block-embed\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/dummyjson.com\/products?limit=20\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Product DTO<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/remote\/ProductDto.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.remote\n\nimport kotlinx.serialization.Serializable\n\n@Serializable\ndata class ProductDto(\n    val id: Int,\n    val title: String,\n    val price: Double,\n    val category: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Response Model<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/remote\/ProductResponse.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.remote\n\nimport kotlinx.serialization.Serializable\n\n@Serializable\ndata class ProductResponse(\n    val products: List&lt;ProductDto&gt;\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The API returns an object containing a products array.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Serialization converts the JSON response into Kotlin objects.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Create the Retrofit API<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/remote\/ProductApi.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.remote\n\nimport retrofit2.http.GET\n\ninterface ProductApi {\n\n    @GET(\"products?limit=20\")\n    suspend fun getProducts(): ProductResponse\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Retrofit performs the HTTP request and converts the response through the configured converter.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Create Data Mappers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/mapper\/ProductMapper.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.mapper\n\nimport com.example.offlineproducts.data.local.ProductEntity\nimport com.example.offlineproducts.data.remote.ProductDto\nimport com.example.offlineproducts.domain.model.Product\n\nfun ProductDto.toEntity(): ProductEntity {\n\n    return ProductEntity(\n        id = id,\n        name = title,\n        price = price,\n        category = category\n    )\n}\n\nfun ProductEntity.toDomain(): Product {\n\n    return Product(\n        id = id,\n        name = name,\n        price = price,\n        category = category\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The remote DTO is converted into a Room entity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Room entity is converted into a domain model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This keeps API and database implementation details outside the domain model.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Create the Repository Interface<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>domain\/repository\/ProductRepository.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.domain.repository\n\nimport com.example.offlineproducts.domain.model.Product\nimport kotlinx.coroutines.flow.Flow\n\ninterface ProductRepository {\n\n    fun observeProducts(): Flow&lt;List&lt;Product&gt;&gt;\n\n    suspend fun refreshProducts()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository exposes two operations:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Observe cached products<\/li>\n\n\n\n<li>Refresh products from the network<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The UI does not need to know how synchronization works.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Create the Repository Implementation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>data\/repository\/ProductRepositoryImpl.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.data.repository\n\nimport com.example.offlineproducts.data.local.ProductDao\nimport com.example.offlineproducts.data.mapper.toDomain\nimport com.example.offlineproducts.data.mapper.toEntity\nimport com.example.offlineproducts.data.remote.ProductApi\nimport com.example.offlineproducts.domain.model.Product\nimport com.example.offlineproducts.domain.repository.ProductRepository\n\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coroutines.flow.map\n\nclass ProductRepositoryImpl(\n    private val api: ProductApi,\n    private val dao: ProductDao\n) : ProductRepository {\n\n    override fun observeProducts(): Flow&lt;List&lt;Product&gt;&gt; {\n\n        return dao.observeProducts()\n            .map { entities -&gt;\n\n                entities.map { entity -&gt;\n                    entity.toDomain()\n                }\n            }\n    }\n\n    override suspend fun refreshProducts() {\n\n        val response = api.getProducts()\n\n        val entities = response.products.map { dto -&gt;\n            dto.toEntity()\n        }\n\n        dao.replaceProducts(entities)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository coordinates the API and database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When refreshProducts() succeeds:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Retrofit fetches products.<\/li>\n\n\n\n<li>DTOs are converted into Room entities.<\/li>\n\n\n\n<li>Room replaces the cached products in a transaction.<\/li>\n\n\n\n<li>Room emits the updated list.<\/li>\n\n\n\n<li>The UI receives the latest data.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Offline Behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If the network request fails before the database transaction, the previously cached products remain available.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The repository allows the exception to propagate so the ViewModel can display a refresh error.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Understanding Cache Synchronization<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A cache stores data locally to reduce repeated network access and support offline functionality.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Cache Strategies<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Strategy<\/th><th>Behavior<\/th><\/tr><tr><td>Network-first<\/td><td>Try network, fall back to cache<\/td><\/tr><tr><td>Cache-first<\/td><td>Use cache when available, otherwise fetch<\/td><\/tr><tr><td>Stale-while-revalidate<\/td><td>Display cache immediately and refresh in background<\/td><\/tr><tr><td>Offline-first<\/td><td>Design reads and supported operations around local availability<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Our product catalog follows a basic stale-while-revalidate approach.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes Room while a network refresh updates the database.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The example does not yet implement time-based cache expiration.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Production applications may track:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Last successful synchronization<\/li>\n\n\n\n<li>Data freshness requirements<\/li>\n\n\n\n<li>Retry attempts<\/li>\n\n\n\n<li>Synchronization status<\/li>\n\n\n\n<li>Pagination state<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Create the UI State<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/products\/ProductUiState.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.presentation.products\n\nimport com.example.offlineproducts.domain.model.Product\n\ndata class ProductUiState(\n    val products: List&lt;Product&gt; = emptyList(),\n    val isLoading: Boolean = true,\n    val isRefreshing: Boolean = false,\n    val errorMessage: String? = null\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use a Data Class?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Offline-first screens often need to display multiple conditions simultaneously.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Cached products are visible.<\/li>\n\n\n\n<li>A refresh is running.<\/li>\n\n\n\n<li>A network error occurs.<\/li>\n\n\n\n<li>Existing data remains available.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A single Loading\/Success\/Error sealed state can be restrictive for these scenarios.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A data class supports combinations of UI conditions.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Create the Product ViewModel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/products\/ProductViewModel.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.presentation.products\n\nimport androidx.lifecycle.ViewModel\nimport androidx.lifecycle.viewModelScope\n\nimport com.example.offlineproducts.domain.repository.ProductRepository\n\nimport kotlinx.coroutines.CancellationException\nimport kotlinx.coroutines.Job\nimport kotlinx.coroutines.flow.MutableStateFlow\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.asStateFlow\nimport kotlinx.coroutines.flow.update\nimport kotlinx.coroutines.launch\n\nclass ProductViewModel(\n    private val repository: ProductRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow(ProductUiState())\n\n    val uiState: StateFlow&lt;ProductUiState&gt; =\n        _uiState.asStateFlow()\n\n    private var refreshJob: Job? = null\n\n    init {\n        observeProducts()\n        refreshProducts()\n    }\n\n    private fun observeProducts() {\n\n        viewModelScope.launch {\n\n            repository.observeProducts()\n                .collect { products -&gt;\n\n                    _uiState.update { state -&gt;\n\n                        state.copy(\n                            products = products,\n                            isLoading = false\n                        )\n                    }\n                }\n        }\n    }\n\n    fun refreshProducts() {\n\n        if (refreshJob?.isActive == true) {\n            return\n        }\n\n        refreshJob = viewModelScope.launch {\n\n            _uiState.update {\n                it.copy(\n                    isRefreshing = true,\n                    errorMessage = null\n                )\n            }\n\n            try {\n\n                repository.refreshProducts()\n\n            } catch (exception: CancellationException) {\n\n                throw exception\n\n            } catch (exception: Exception) {\n\n                _uiState.update {\n                    it.copy(\n                        errorMessage =\n                            \"Unable to refresh. Showing cached data.\"\n                    )\n                }\n\n            } finally {\n\n                _uiState.update {\n                    it.copy(\n                        isRefreshing = false\n                    )\n                }\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel performs two independent operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Database Observation<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">observeProducts() collects Room updates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Network Synchronization<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">refreshProducts() attempts to download the latest products.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If synchronization fails, existing cached products remain visible.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid cancelling long-lived database observation when starting a refresh.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Database observation and synchronization are separate responsibilities.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Create the Jetpack Compose Screen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: <code>presentation\/products\/ProductScreen.kt<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.offlineproducts.presentation.products\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.lazy.LazyColumn\nimport androidx.compose.foundation.lazy.items\nimport androidx.compose.material3.*\nimport androidx.compose.runtime.*\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.unit.dp\n\nimport androidx.lifecycle.compose.collectAsStateWithLifecycle\n\nimport com.example.offlineproducts.domain.model.Product\n\n@OptIn(ExperimentalMaterial3Api::class)\n@Composable\nfun ProductScreen(\n    viewModel: ProductViewModel\n) {\n\n    val state by viewModel.uiState\n        .collectAsStateWithLifecycle()\n\n    Scaffold(\n        topBar = {\n\n            TopAppBar(\n                title = {\n                    Text(\"Offline Product Catalog\")\n                }\n            )\n        }\n    ) { paddingValues -&gt;\n\n        Column(\n            modifier = Modifier\n                .fillMaxSize()\n                .padding(paddingValues)\n        ) {\n\n            Row(\n                modifier = Modifier\n                    .fillMaxWidth()\n                    .padding(16.dp),\n                horizontalArrangement =\n                    Arrangement.SpaceBetween,\n                verticalAlignment =\n                    Alignment.CenterVertically\n            ) {\n\n                Text(\n                    text = \"Products\",\n                    style = MaterialTheme.typography.titleLarge\n                )\n\n                Button(\n                    onClick = viewModel::refreshProducts,\n                    enabled = !state.isRefreshing\n                ) {\n\n                    Text(\n                        if (state.isRefreshing) {\n                            \"Refreshing...\"\n                        } else {\n                            \"Refresh\"\n                        }\n                    )\n                }\n            }\n\n            if (state.isRefreshing) {\n\n                LinearProgressIndicator(\n                    modifier = Modifier.fillMaxWidth()\n                )\n            }\n\n            state.errorMessage?.let { message -&gt;\n\n                Text(\n                    text = message,\n                    color = MaterialTheme.colorScheme.error,\n                    modifier = Modifier.padding(16.dp)\n                )\n            }\n\n            Box(\n                modifier = Modifier.fillMaxSize()\n            ) {\n\n                when {\n\n                    state.isLoading -&gt; {\n\n                        CircularProgressIndicator(\n                            modifier = Modifier.align(\n                                Alignment.Center\n                            )\n                        )\n                    }\n\n                    state.products.isEmpty() -&gt; {\n\n                        Text(\n                            text = \"No products available\",\n                            modifier = Modifier.align(\n                                Alignment.Center\n                            )\n                        )\n                    }\n\n                    else -&gt; {\n\n                        LazyColumn(\n                            contentPadding = PaddingValues(16.dp),\n                            verticalArrangement =\n                                Arrangement.spacedBy(12.dp)\n                        ) {\n\n                            items(\n                                items = state.products,\n                                key = { it.id }\n                            ) { product -&gt;\n\n                                ProductCard(product)\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n@Composable\nfun ProductCard(\n    product: Product\n) {\n\n    Card(\n        modifier = Modifier.fillMaxWidth()\n    ) {\n\n        Column(\n            modifier = Modifier.padding(16.dp),\n            verticalArrangement =\n                Arrangement.spacedBy(8.dp)\n        ) {\n\n            Text(\n                text = product.name,\n                style = MaterialTheme.typography.titleMedium\n            )\n\n            Text(\n                text = product.category\n            )\n\n            Text(\n                text = \"\u20b9${product.price}\",\n                color = MaterialTheme.colorScheme.primary\n            )\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The UI observes StateFlow using collectAsStateWithLifecycle().<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Cached products remain visible while a refresh is running.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If a network request fails, an error message appears without removing existing products.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. Configure Retrofit and Room<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For this tutorial, we&#8217;ll use manual dependency injection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Retrofit Setup<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val json = Json {\n    ignoreUnknownKeys = true\n}\n\nval retrofit = Retrofit.Builder()\n    .baseUrl(\"https:\/\/dummyjson.com\/\")\n    .addConverterFactory(\n        json.asConverterFactory(\n            \"application\/json\".toMediaType()\n        )\n    )\n    .build()\n\nval api = retrofit.create(ProductApi::class.java)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Room Setup<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val database = Room.databaseBuilder(\n    applicationContext,\n    AppDatabase::class.java,\n    \"products_database\"\n).build()\n\nval dao = database.productDao()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Repository Setup<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val repository = ProductRepositoryImpl(\n    api = api,\n    dao = dao\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Retrofit, Room, and repository instances should generally be shared rather than recreated for every screen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For production applications, use application-level dependency management such as Hilt.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">26. Create the ViewModel Factory<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModelFactory(\n    private val repository: ProductRepository\n) : ViewModelProvider.Factory {\n\n    override fun &lt;T : ViewModel&gt; create(\n        modelClass: Class&lt;T&gt;\n    ): T {\n\n        if (\n            modelClass.isAssignableFrom(\n                ProductViewModel::class.java\n            )\n        ) {\n\n            @Suppress(\"UNCHECKED_CAST\")\n            return ProductViewModel(repository) as T\n        }\n\n        throw IllegalArgumentException(\n            \"Unknown ViewModel class\"\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The factory injects ProductRepository into ProductViewModel.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">27. Create MainActivity<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class MainActivity : ComponentActivity() {\n\n    override fun onCreate(\n        savedInstanceState: Bundle?\n    ) {\n\n        super.onCreate(savedInstanceState)\n\n        val json = Json {\n            ignoreUnknownKeys = true\n        }\n\n        val retrofit = Retrofit.Builder()\n            .baseUrl(\"https:\/\/dummyjson.com\/\")\n            .addConverterFactory(\n                json.asConverterFactory(\n                    \"application\/json\".toMediaType()\n                )\n            )\n            .build()\n\n        val api = retrofit.create(ProductApi::class.java)\n\n        val database = Room.databaseBuilder(\n            applicationContext,\n            AppDatabase::class.java,\n            \"products_database\"\n        ).build()\n\n        val repository = ProductRepositoryImpl(\n            api = api,\n            dao = database.productDao()\n        )\n\n        val factory = ProductViewModelFactory(repository)\n\n        setContent {\n\n            MaterialTheme {\n\n                val viewModel: ProductViewModel =\n                    viewModel(factory = factory)\n\n                ProductScreen(viewModel)\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">MainActivity configures the application dependencies and displays the Compose screen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is intentionally simple for educational purposes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For production, move shared dependency construction into an application-level container or Hilt configuration.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. Expected Application UI<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">First Launch<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|      Offline Product Catalog   |\n|                                |\n| Products             &#91;Refresh] |\n|                                |\n|              \u25cb                 |\n|                                |\n|        Loading products...     |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Products Loaded<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|      Offline Product Catalog   |\n|                                |\n| Products             &#91;Refresh] |\n|                                |\n| +----------------------------+ |\n| | Essence Mascara            | |\n| | beauty                     | |\n| | \u20b99.99                      | |\n| +----------------------------+ |\n|                                |\n| +----------------------------+ |\n| | Eyeshadow Palette          | |\n| | beauty                     | |\n| | \u20b919.99                     | |\n| +----------------------------+ |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Offline with Cached Products<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|      Offline Product Catalog   |\n|                                |\n| Products             &#91;Refresh] |\n|                                |\n| Unable to refresh.             |\n| Showing cached data.           |\n|                                |\n| +----------------------------+ |\n| | Essence Mascara            | |\n| | beauty                     | |\n| | \u20b99.99                      | |\n| +----------------------------+ |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Previously cached products remain visible even if the network is unavailable.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Understanding Cache Invalidation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Cached data eventually becomes outdated.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Cache invalidation determines when data should be refreshed or replaced.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Approaches<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Time-Based Expiration<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Refresh data after a specified duration.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>User-Initiated Refresh<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Refresh when the user taps a button.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Event-Based Invalidation<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Refresh when a relevant application event occurs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Server-Driven Updates<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Refresh based on server notifications or synchronization signals.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun shouldRefresh(\n    lastSyncTime: Long,\n    currentTime: Long\n): Boolean {\n\n    val cacheDuration = 15 * 60 * 1000L\n\n    return currentTime - lastSyncTime &gt; cacheDuration\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The function checks whether more than 15 minutes have passed since the previous synchronization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a reliable time source and handle clock changes appropriately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For persisted timestamps, use a clearly defined timestamp representation.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. Handling Network Failures<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Network requests can fail for many reasons.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No internet connection<\/li>\n\n\n\n<li>Connection timeout<\/li>\n\n\n\n<li>Server errors<\/li>\n\n\n\n<li>Invalid responses<\/li>\n\n\n\n<li>Authentication failure<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun refreshSafely(\n    repository: ProductRepository\n): Result&lt;Unit&gt; {\n\n    return try {\n\n        repository.refreshProducts()\n\n        Result.success(Unit)\n\n    } catch (exception: CancellationException) {\n\n        throw exception\n\n    } catch (exception: Exception) {\n\n        Result.failure(exception)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The function converts ordinary failures into Result values while preserving coroutine cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not delete cached data simply because a network request fails.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">31. Repository Pattern with Kotlin Flow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Flow is especially useful for reactive data access.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun observeProducts(): Flow&lt;List&lt;Product&gt;&gt; {\n\n    return dao.observeProducts()\n        .map { entities -&gt;\n\n            entities.map { it.toDomain() }\n        }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The repository exposes database updates as a Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel collects those updates.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI receives updated state automatically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Reactive UI<\/li>\n\n\n\n<li>Automatic database updates<\/li>\n\n\n\n<li>Clear separation of responsibilities<\/li>\n\n\n\n<li>Natural StateFlow integration<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">32. Testing the Repository Pattern<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Repositories can be tested using fake APIs and local data sources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Fake Repository<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class FakeProductRepository : ProductRepository {\n\n    private val products =\n        MutableStateFlow&lt;List&lt;Product&gt;&gt;(emptyList())\n\n    override fun observeProducts(): Flow&lt;List&lt;Product&gt;&gt; {\n        return products\n    }\n\n    override suspend fun refreshProducts() {\n\n        products.value = listOf(\n            Product(\n                id = 1,\n                name = \"Test Product\",\n                price = 100.0,\n                category = \"Testing\"\n            )\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `refresh updates observed products`() = runTest {\n\n    val repository = FakeProductRepository()\n\n    repository.refreshProducts()\n\n    val products = repository.observeProducts().first()\n\n    assertEquals(1, products.size)\n\n    assertEquals(\n        \"Test Product\",\n        products.first().name\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies that refreshing the repository updates the observable data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Also test the real repository implementation using a fake API and an in-memory Room database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Important cases include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Successful synchronization<\/li>\n\n\n\n<li>Network failure with existing cache<\/li>\n\n\n\n<li>Empty API response<\/li>\n\n\n\n<li>Database transaction failure<\/li>\n\n\n\n<li>Duplicate records<\/li>\n\n\n\n<li>Cancellation during refresh<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">33. Advanced Offline-First Considerations<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Production offline-first applications often need more than basic caching.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Pagination<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Large datasets should not always be downloaded at once.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Consider Paging 3 with Room and RemoteMediator.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Background Synchronization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use WorkManager for deferrable, persistent synchronization that should survive application restarts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conflict Resolution<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If users can modify data offline, define how local and server changes are reconciled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Authentication<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Handle expired tokens and authorization errors without exposing sensitive information.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Retry Policies<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use bounded retries and exponential backoff for appropriate transient failures.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Data Freshness<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Track synchronization metadata and define acceptable staleness.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Database Migrations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Maintain explicit Room migration strategies as the schema changes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Observability<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Monitor synchronization failures and performance without logging sensitive user data.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">34. Common Repository Pattern Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Fetching API Data Directly in Composables<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep network operations outside UI rendering functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Exposing Retrofit DTOs Throughout the Application<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use mapping when source-specific schemas should not leak into other layers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Treating Network and Database as Competing Sources<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Define one authoritative source for each data type.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Deleting Cached Data on Network Failure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Preserve useful cached data when synchronization fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Ignoring Coroutine Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Always propagate CancellationException.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Recreating Repositories Repeatedly<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use appropriately scoped shared instances.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Performing Unnecessary Network Requests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use cache freshness and synchronization policies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Replacing Complete Tables with Partial API Results<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Understand pagination and API completeness before replacing cached records.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Ignoring Database Transactions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use transactions when multiple database changes must succeed atomically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Overengineering Simple Data Access<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep abstractions proportional to application complexity.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">35. Repository Pattern Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Follow these recommendations:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Define clear repository responsibilities.<\/li>\n\n\n\n<li>Use constructor injection.<\/li>\n\n\n\n<li>Keep ViewModels independent of concrete data sources.<\/li>\n\n\n\n<li>Use Room as a source of truth when appropriate.<\/li>\n\n\n\n<li>Expose reactive data through Flow.<\/li>\n\n\n\n<li>Keep network synchronization separate from database observation.<\/li>\n\n\n\n<li>Preserve cached data on network failures.<\/li>\n\n\n\n<li>Use database transactions for atomic updates.<\/li>\n\n\n\n<li>Map DTOs and entities where useful.<\/li>\n\n\n\n<li>Handle coroutine cancellation correctly.<\/li>\n\n\n\n<li>Track data freshness.<\/li>\n\n\n\n<li>Avoid duplicate refresh operations.<\/li>\n\n\n\n<li>Implement bounded retry strategies.<\/li>\n\n\n\n<li>Use WorkManager for suitable persistent background work.<\/li>\n\n\n\n<li>Test success, failure, and offline behavior.<\/li>\n\n\n\n<li>Avoid unnecessary abstraction layers.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">36. Repository Pattern Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Concept<\/th><th>Purpose<\/th><\/tr><tr><td>Repository Pattern<\/td><td>Centralized data access<\/td><\/tr><tr><td>Repository Interface<\/td><td>Data access contract<\/td><\/tr><tr><td>Repository Implementation<\/td><td>Concrete data management<\/td><\/tr><tr><td>Remote Data Source<\/td><td>Network access<\/td><\/tr><tr><td>Local Data Source<\/td><td>Local storage<\/td><\/tr><tr><td>Single Source of Truth<\/td><td>Authoritative data source<\/td><\/tr><tr><td>Offline-First<\/td><td>Prioritize offline availability<\/td><\/tr><tr><td>Room<\/td><td>Local relational database<\/td><\/tr><tr><td>Retrofit<\/td><td>HTTP API client<\/td><\/tr><tr><td>DTO<\/td><td>External data representation<\/td><\/tr><tr><td>Mapper<\/td><td>Convert between models<\/td><\/tr><tr><td>Flow<\/td><td>Reactive data stream<\/td><\/tr><tr><td>StateFlow<\/td><td>Observable UI state<\/td><\/tr><tr><td>Cache Invalidation<\/td><td>Determine when data is stale<\/td><\/tr><tr><td>WorkManager<\/td><td>Persistent deferrable background work<\/td><\/tr><tr><td>RemoteMediator<\/td><td>Coordinate Paging with network and database<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">37. Practical Exercises<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Basic Repository<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a UserRepository interface.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Room Database<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store users locally using Room.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: Retrofit API<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Fetch users from a REST endpoint.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: Single Source of Truth<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Expose users only from the local database.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: Offline Support<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Disable internet connectivity and verify cached data remains visible.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Manual Refresh<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add a Refresh button.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: Error Handling<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Display a synchronization error without removing cached data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: Cache Expiration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Implement a 15-minute refresh policy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: Repository Testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test synchronization with fake dependencies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Complete Application<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Build the full offline-first product catalog and extend it with search and filtering.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">38. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is the Repository Pattern in Android?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Repository Pattern provides a consistent interface for accessing and managing application data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why use repositories with MVVM?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Repositories separate data access from presentation logic and make ViewModels easier to test.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Single Source of Truth?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is the authoritative source used to determine the current state of particular application data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is offline-first architecture?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Offline-first architecture designs applications to provide useful functionality without requiring continuous network connectivity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should Room always be the source of truth?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Room is a practical choice for many offline-first applications, but the correct source of truth depends on application requirements.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can repositories use both Retrofit and Room?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A repository can coordinate remote API requests and local database operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why use Flow with Room?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Flow allows applications to observe database changes reactively.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should a repository return Flow or suspend functions?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Flow for data that should be observed over time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use suspend functions for operations that return a single result or perform an action.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I prevent duplicate network requests?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use appropriate synchronization ownership, cache policies, and concurrency controls.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is the Repository Pattern required for every Android app?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is useful when separating data access improves maintainability, testing, or scalability.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What We&#8217;ve Learned<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we explored:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Repository Pattern fundamentals<\/li>\n\n\n\n<li>MVVM and Clean Architecture integration<\/li>\n\n\n\n<li>Repository interfaces and implementations<\/li>\n\n\n\n<li>Local and remote data sources<\/li>\n\n\n\n<li>Single Source of Truth<\/li>\n\n\n\n<li>Offline-first architecture<\/li>\n\n\n\n<li>Room database integration<\/li>\n\n\n\n<li>Retrofit API integration<\/li>\n\n\n\n<li>Kotlin Flow<\/li>\n\n\n\n<li>Data mapping<\/li>\n\n\n\n<li>Caching strategies<\/li>\n\n\n\n<li>Cache invalidation<\/li>\n\n\n\n<li>Network synchronization<\/li>\n\n\n\n<li>Error handling<\/li>\n\n\n\n<li>Repository testing<\/li>\n\n\n\n<li>Production best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The Repository Pattern is an important building block of maintainable Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining Room, Retrofit, Kotlin Flow, ViewModel, and Jetpack Compose, developers can build applications that display cached data quickly and remain useful during network interruptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most important principle is to define clear data ownership and keep synchronization logic separate from UI rendering.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In our next tutorial:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Article 41 \u2014 Android ViewModel &amp; UI State Management with StateFlow and Jetpack Compose: Complete Guide<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll learn:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ViewModel lifecycle<\/li>\n\n\n\n<li>UI state modeling<\/li>\n\n\n\n<li>MutableStateFlow and StateFlow<\/li>\n\n\n\n<li>State hoisting<\/li>\n\n\n\n<li>Unidirectional Data Flow<\/li>\n\n\n\n<li>SavedStateHandle<\/li>\n\n\n\n<li>Loading, success, and error states<\/li>\n\n\n\n<li>One-time UI events<\/li>\n\n\n\n<li>Lifecycle-aware collection<\/li>\n\n\n\n<li>State restoration<\/li>\n\n\n\n<li>ViewModel testing<\/li>\n\n\n\n<li>Practical Android mini-project<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Happy Coding!<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Continue learning modern Android development with <strong>Moiks Developer Blog<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Build offline-first Android apps using the Repository Pattern, Kotlin, Jetpack Compose, Room, Retrofit, and Flow. Learn single source of truth, caching, synchronization, and production best practices.<\/p>\n","protected":false},"author":1,"featured_media":182,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":1,"footnotes":""},"categories":[3,333,8],"tags":[],"class_list":["post-181","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-development","category-android-tutorials","category-android-architecture"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/181","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=181"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/181\/revisions"}],"predecessor-version":[{"id":183,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/181\/revisions\/183"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/182"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=181"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=181"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=181"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}