{"id":210,"date":"2026-10-21T19:00:00","date_gmt":"2026-10-21T19:00:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=210"},"modified":"2026-11-06T08:48:21","modified_gmt":"2026-11-06T08:48:21","slug":"datastore-in-android-with-kotlin-jetpack-compose-preferences-proto-datastore-reactive-settings","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/datastore-in-android-with-kotlin-jetpack-compose-preferences-proto-datastore-reactive-settings\/","title":{"rendered":"DataStore in Android with Kotlin &#038; Jetpack Compose: Preferences, Proto DataStore &#038; Reactive Settings"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Modern Android applications need to remember user preferences and small amounts of persistent information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Dark mode preferences<\/li>\n\n\n\n<li>Notification settings<\/li>\n\n\n\n<li>Selected language<\/li>\n\n\n\n<li>Onboarding completion<\/li>\n\n\n\n<li>Default sorting options<\/li>\n\n\n\n<li>User-selected themes<\/li>\n\n\n\n<li>Application display preferences<\/li>\n\n\n\n<li>Feature configuration<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Traditionally, Android developers used SharedPreferences to store this information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, SharedPreferences has limitations, including synchronous APIs and less convenient integration with Kotlin Coroutines and Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Android Jetpack provides <strong>DataStore<\/strong>, a modern solution for asynchronous, persistent, and reactive data storage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll learn Preferences DataStore and Proto DataStore, understand how they differ, and build a practical Settings Manager application using Kotlin, Hilt, MVVM, StateFlow, and Jetpack Compose.<\/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 Jetpack DataStore is<\/li>\n\n\n\n<li>SharedPreferences vs DataStore<\/li>\n\n\n\n<li>Preferences DataStore<\/li>\n\n\n\n<li>Proto DataStore<\/li>\n\n\n\n<li>Kotlin Flow integration<\/li>\n\n\n\n<li>Reading and writing preferences<\/li>\n\n\n\n<li>Type-safe preference keys<\/li>\n\n\n\n<li>Reactive UI updates<\/li>\n\n\n\n<li>Repository Pattern<\/li>\n\n\n\n<li>Hilt dependency injection<\/li>\n\n\n\n<li>MVVM architecture<\/li>\n\n\n\n<li>StateFlow and stateIn()<\/li>\n\n\n\n<li>Jetpack Compose settings UI<\/li>\n\n\n\n<li>Dark mode persistence<\/li>\n\n\n\n<li>Notification preferences<\/li>\n\n\n\n<li>Onboarding completion state<\/li>\n\n\n\n<li>DataStore error handling<\/li>\n\n\n\n<li>SharedPreferences migration<\/li>\n\n\n\n<li>DataStore testing<\/li>\n\n\n\n<li>Performance considerations<\/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 DataStore?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore is an Android Jetpack library designed for storing small amounts of application data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It provides asynchronous APIs and integrates with Kotlin Coroutines and Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore supports two main approaches:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Preferences DataStore<\/li>\n\n\n\n<li>Proto DataStore<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Preferences DataStore<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Stores key-value pairs without requiring a predefined schema.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Proto DataStore<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Stores structured, strongly typed objects using Protocol Buffers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both approaches support asynchronous reads and transactional updates.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Why Use DataStore Instead of SharedPreferences?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedPreferences is a familiar Android storage API, but it has limitations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">SharedPreferences Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val preferences = context.getSharedPreferences(\n    \"settings\",\n    Context.MODE_PRIVATE\n)\n\nval darkMode = preferences.getBoolean(\n    \"dark_mode\",\n    false\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This reads a preference synchronously.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">DataStore Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val darkModeFlow: Flow&lt;Boolean&gt; =\n    context.dataStore.data.map { preferences -&gt;\n        preferences&#91;DARK_MODE] ?: false\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore exposes a Flow that emits updated values when preferences change.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>SharedPreferences<\/th><th>DataStore<\/th><\/tr><tr><td>Asynchronous API<\/td><td>Limited<\/td><td>Yes<\/td><\/tr><tr><td>Kotlin Flow<\/td><td>Manual integration<\/td><td>Built-in<\/td><\/tr><tr><td>Transactional updates<\/td><td>Limited<\/td><td>Yes<\/td><\/tr><tr><td>Structured schema<\/td><td>No<\/td><td>Proto DataStore<\/td><\/tr><tr><td>Coroutine support<\/td><td>Manual<\/td><td>Built-in<\/td><\/tr><tr><td>Reactive Compose integration<\/td><td>Manual<\/td><td>Straightforward<\/td><\/tr><tr><td>Persistent key-value storage<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For new Kotlin-based applications, DataStore is generally preferable for small settings and preferences.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For complex relational data, use Room instead.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. DataStore vs Room<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore and Room serve different purposes.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Requirement<\/th><th>Recommended Storage<\/th><\/tr><tr><td>Dark mode setting<\/td><td>DataStore<\/td><\/tr><tr><td>Notification enabled<\/td><td>DataStore<\/td><\/tr><tr><td>Onboarding completed<\/td><td>DataStore<\/td><\/tr><tr><td>Selected app language<\/td><td>DataStore<\/td><\/tr><tr><td>Thousands of transactions<\/td><td>Room<\/td><\/tr><tr><td>Product catalog<\/td><td>Room<\/td><\/tr><tr><td>Relational records<\/td><td>Room<\/td><\/tr><tr><td>Searchable history<\/td><td>Room<\/td><\/tr><tr><td>Complex database queries<\/td><td>Room<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore is not a replacement for a relational database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use it for small persistent data that does not require relational queries or partial record updates.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Understanding DataStore Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A typical application architecture looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> <code>       Jetpack Compose\n               |\n               v\n            ViewModel\n               |\n               v\n        SettingsRepository\n               |\n               v\n            DataStore\n               |\n               v\n       Persistent Storage<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When a preference changes:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>User Changes Setting\n         |\n         v\n      ViewModel\n         |\n         v\n      Repository\n         |\n         v\n    DataStore.edit()\n         |\n         v\n    DataStore Flow\n         |\n         v\n     Compose Recomposition<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The UI automatically reacts to stored preference changes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Add DataStore Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In your app module, add:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    implementation(\n        \"androidx.datastore:datastore-preferences:&lt;datastore-version&gt;\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace the version placeholder with a compatible stable release.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For our application, also configure:<\/p>\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>Lifecycle ViewModel<\/li>\n\n\n\n<li>Lifecycle Runtime Compose<\/li>\n\n\n\n<li>Kotlin Coroutines<\/li>\n\n\n\n<li>Hilt<\/li>\n\n\n\n<li>KSP<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll use Preferences DataStore for the main project and introduce Proto DataStore afterward.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Create a Preferences DataStore Instance<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The recommended Kotlin property-delegate approach is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val Context.dataStore by preferencesDataStore(\n    name = \"app_settings\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Required imports:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import android.content.Context\nimport androidx.datastore.preferences.preferencesDataStore<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Declare the delegate once at the top level of a Kotlin file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not create multiple DataStore instances for the same file within one process.<\/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 Preference Keys<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Preferences DataStore uses typed keys.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val DARK_MODE = booleanPreferencesKey(\n    \"dark_mode\"\n)\n\nval USER_NAME = stringPreferencesKey(\n    \"user_name\"\n)\n\nval FONT_SIZE = intPreferencesKey(\n    \"font_size\"\n)\n\nval LAST_SYNC = longPreferencesKey(\n    \"last_sync\"\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Supported Preference Types<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Preferences DataStore supports common types such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Boolean<\/li>\n\n\n\n<li>Int<\/li>\n\n\n\n<li>Long<\/li>\n\n\n\n<li>Float<\/li>\n\n\n\n<li>Double<\/li>\n\n\n\n<li>String<\/li>\n\n\n\n<li>Set of strings<\/li>\n\n\n\n<li>Byte arrays<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep preference keys centralized to avoid inconsistent names across the application.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Reading Preferences with Flow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore exposes preferences through Flow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val darkModeFlow: Flow&lt;Boolean&gt; =\n    context.dataStore.data.map { preferences -&gt;\n\n        preferences&#91;DARK_MODE] ?: false\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>DataStore reads stored preferences.<\/li>\n\n\n\n<li>map() extracts the requested value.<\/li>\n\n\n\n<li>The default value is used when the key is absent.<\/li>\n\n\n\n<li>The Flow emits updated values when stored data changes.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This makes DataStore especially useful with Jetpack Compose.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Writing Preferences<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use edit() to update Preferences DataStore.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun setDarkMode(\n    enabled: Boolean\n) {\n\n    context.dataStore.edit { preferences -&gt;\n\n        preferences&#91;DARK_MODE] = enabled\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">edit() performs an atomic read-modify-write transaction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The updated value is persisted and subsequently emitted through the DataStore Flow.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Removing Preferences<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A stored preference can be removed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun removeDarkMode() {\n\n    context.dataStore.edit { preferences -&gt;\n\n        preferences.remove(DARK_MODE)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Clear All Preferences<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun clearSettings() {\n\n    context.dataStore.edit { preferences -&gt;\n\n        preferences.clear()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Clearing preferences removes all values stored in that DataStore.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use this operation carefully.<\/p>\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: Settings Manager with DataStore and Jetpack Compose<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s build a modern Settings Manager application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Persistent dark mode<\/li>\n\n\n\n<li>Notification preference<\/li>\n\n\n\n<li>Username setting<\/li>\n\n\n\n<li>Font size preference<\/li>\n\n\n\n<li>Onboarding completion state<\/li>\n\n\n\n<li>Reset settings<\/li>\n\n\n\n<li>Reactive Compose UI<\/li>\n\n\n\n<li>Hilt integration<\/li>\n\n\n\n<li>MVVM architecture<\/li>\n\n\n\n<li>StateFlow-based UI state<\/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>Preferences DataStore<\/li>\n\n\n\n<li>Kotlin Flow<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>Hilt<\/li>\n\n\n\n<li>ViewModel<\/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\">11. Recommended Project Structure<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>com.example.datastoresettings\/\n\u2502\n\u251c\u2500\u2500 SettingsApplication.kt\n\u251c\u2500\u2500 MainActivity.kt\n\u2502\n\u251c\u2500\u2500 data\/\n\u2502   \u251c\u2500\u2500 AppDataStore.kt\n\u2502   \u251c\u2500\u2500 SettingsPreferences.kt\n\u2502   \u2514\u2500\u2500 SettingsRepositoryImpl.kt\n\u2502\n\u251c\u2500\u2500 domain\/\n\u2502   \u251c\u2500\u2500 model\/\n\u2502   \u2502   \u2514\u2500\u2500 AppSettings.kt\n\u2502   \u2502\n\u2502   \u2514\u2500\u2500 repository\/\n\u2502       \u2514\u2500\u2500 SettingsRepository.kt\n\u2502\n\u251c\u2500\u2500 di\/\n\u2502   \u2514\u2500\u2500 SettingsModule.kt\n\u2502\n\u2514\u2500\u2500 presentation\/\n    \u251c\u2500\u2500 SettingsViewModel.kt\n    \u2514\u2500\u2500 SettingsScreen.kt<\/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. Step 1 \u2014 Create Application Class<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: SettingsApplication.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings\n\nimport android.app.Application\nimport dagger.hilt.android.HiltAndroidApp\n\n@HiltAndroidApp\nclass SettingsApplication : Application()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Register it in AndroidManifest.xml:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;application\n    android:name=\".SettingsApplication\"\n    ... &gt;\n&lt;\/application&gt;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Keep the remaining application configuration generated by Android Studio.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Step 2 \u2014 Create DataStore Delegate<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: data\/AppDataStore.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.data\n\nimport android.content.Context\n\nimport androidx.datastore.preferences.preferencesDataStore\n\nval Context.appDataStore by preferencesDataStore(\n    name = \"app_settings\"\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This creates one Preferences DataStore delegate for the application settings file.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Step 3 \u2014 Define Preference Keys<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: data\/SettingsPreferences.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.data\n\nimport androidx.datastore.preferences.core.booleanPreferencesKey\nimport androidx.datastore.preferences.core.intPreferencesKey\nimport androidx.datastore.preferences.core.stringPreferencesKey\n\nobject SettingsPreferences {\n\n    val DARK_MODE = booleanPreferencesKey(\n        \"dark_mode\"\n    )\n\n    val NOTIFICATIONS_ENABLED = booleanPreferencesKey(\n        \"notifications_enabled\"\n    )\n\n    val USER_NAME = stringPreferencesKey(\n        \"user_name\"\n    )\n\n    val FONT_SIZE = intPreferencesKey(\n        \"font_size\"\n    )\n\n    val ONBOARDING_COMPLETED = booleanPreferencesKey(\n        \"onboarding_completed\"\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">All preference keys are centralized in one object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This improves maintainability.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Step 4 \u2014 Create AppSettings Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: domain\/model\/AppSettings.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.domain.model\n\ndata class AppSettings(\n    val darkMode: Boolean = false,\n    val notificationsEnabled: Boolean = true,\n    val userName: String = \"\",\n    val fontSize: Int = 16,\n    val onboardingCompleted: Boolean = false\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">AppSettings represents the application&#8217;s stored preferences as one immutable model.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Step 5 \u2014 Create Repository Interface<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: domain\/repository\/SettingsRepository.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.domain.repository\n\nimport com.example.datastoresettings.domain.model.AppSettings\n\nimport kotlinx.coroutines.flow.Flow\n\ninterface SettingsRepository {\n\n    val settings: Flow&lt;AppSettings&gt;\n\n    suspend fun setDarkMode(enabled: Boolean)\n\n    suspend fun setNotificationsEnabled(enabled: Boolean)\n\n    suspend fun setUserName(name: String)\n\n    suspend fun setFontSize(size: Int)\n\n    suspend fun setOnboardingCompleted(completed: Boolean)\n\n    suspend fun resetSettings()\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 defines the operations available to the rest of the application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The presentation layer does not need to know how DataStore works internally.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Step 6 \u2014 Implement SettingsRepository<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: data\/SettingsRepositoryImpl.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.data\n\nimport android.content.Context\n\nimport androidx.datastore.preferences.core.edit\n\nimport com.example.datastoresettings.domain.model.AppSettings\nimport com.example.datastoresettings.domain.repository.SettingsRepository\n\nimport dagger.hilt.android.qualifiers.ApplicationContext\n\nimport javax.inject.Inject\n\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coroutines.flow.catch\nimport kotlinx.coroutines.flow.map\n\nimport java.io.IOException\n\nclass SettingsRepositoryImpl @Inject constructor(\n    @ApplicationContext private val context: Context\n) : SettingsRepository {\n\n    override val settings: Flow&lt;AppSettings&gt; =\n        context.appDataStore.data\n            .catch { exception -&gt;\n\n                if (exception is IOException) {\n\n                    emit(\n                        androidx.datastore.preferences.core.emptyPreferences()\n                    )\n\n                } else {\n\n                    throw exception\n                }\n            }\n            .map { preferences -&gt;\n\n                AppSettings(\n                    darkMode = preferences&#91;\n                        SettingsPreferences.DARK_MODE\n                    ] ?: false,\n\n                    notificationsEnabled = preferences&#91;\n                        SettingsPreferences.NOTIFICATIONS_ENABLED\n                    ] ?: true,\n\n                    userName = preferences&#91;\n                        SettingsPreferences.USER_NAME\n                    ] ?: \"\",\n\n                    fontSize = preferences&#91;\n                        SettingsPreferences.FONT_SIZE\n                    ] ?: 16,\n\n                    onboardingCompleted = preferences&#91;\n                        SettingsPreferences.ONBOARDING_COMPLETED\n                    ] ?: false\n                )\n            }\n\n    override suspend fun setDarkMode(\n        enabled: Boolean\n    ) {\n\n        context.appDataStore.edit { preferences -&gt;\n\n            preferences&#91;\n                SettingsPreferences.DARK_MODE\n            ] = enabled\n        }\n    }\n\n    override suspend fun setNotificationsEnabled(\n        enabled: Boolean\n    ) {\n\n        context.appDataStore.edit { preferences -&gt;\n\n            preferences&#91;\n                SettingsPreferences.NOTIFICATIONS_ENABLED\n            ] = enabled\n        }\n    }\n\n    override suspend fun setUserName(\n        name: String\n    ) {\n\n        context.appDataStore.edit { preferences -&gt;\n\n            preferences&#91;\n                SettingsPreferences.USER_NAME\n            ] = name\n        }\n    }\n\n    override suspend fun setFontSize(\n        size: Int\n    ) {\n\n        context.appDataStore.edit { preferences -&gt;\n\n            preferences&#91;\n                SettingsPreferences.FONT_SIZE\n            ] = size.coerceIn(12, 24)\n        }\n    }\n\n    override suspend fun setOnboardingCompleted(\n        completed: Boolean\n    ) {\n\n        context.appDataStore.edit { preferences -&gt;\n\n            preferences&#91;\n                SettingsPreferences.ONBOARDING_COMPLETED\n            ] = completed\n        }\n    }\n\n    override suspend fun resetSettings() {\n\n        context.appDataStore.edit { preferences -&gt;\n\n            preferences.clear()\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 repository:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Reads stored preferences.<\/li>\n\n\n\n<li>Converts them into AppSettings.<\/li>\n\n\n\n<li>Exposes a reactive Flow.<\/li>\n\n\n\n<li>Updates values using edit().<\/li>\n\n\n\n<li>Handles recoverable read I\/O errors.<\/li>\n\n\n\n<li>Supports resetting settings.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In production, log recoverable read errors and surface an appropriate error state when needed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Emitting default preferences after an IOException does not repair a damaged storage file.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Step 7 \u2014 Create Hilt Repository Module<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: di\/SettingsModule.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.di\n\nimport com.example.datastoresettings.data.SettingsRepositoryImpl\nimport com.example.datastoresettings.domain.repository.SettingsRepository\n\nimport dagger.Binds\nimport dagger.Module\nimport dagger.hilt.InstallIn\nimport dagger.hilt.components.SingletonComponent\n\nimport javax.inject.Singleton\n\n@Module\n@InstallIn(SingletonComponent::class)\nabstract class SettingsModule {\n\n    @Binds\n    @Singleton\n    abstract fun bindSettingsRepository(\n        implementation: SettingsRepositoryImpl\n    ): SettingsRepository\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Hilt injects SettingsRepositoryImpl whenever SettingsRepository is requested.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Step 8 \u2014 Create SettingsViewModel<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: presentation\/SettingsViewModel.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.presentation\n\nimport androidx.lifecycle.ViewModel\nimport androidx.lifecycle.viewModelScope\n\nimport com.example.datastoresettings.domain.model.AppSettings\nimport com.example.datastoresettings.domain.repository.SettingsRepository\n\nimport dagger.hilt.android.lifecycle.HiltViewModel\n\nimport javax.inject.Inject\n\nimport kotlinx.coroutines.flow.SharingStarted\nimport kotlinx.coroutines.flow.StateFlow\nimport kotlinx.coroutines.flow.stateIn\nimport kotlinx.coroutines.launch\n\n@HiltViewModel\nclass SettingsViewModel @Inject constructor(\n    private val repository: SettingsRepository\n) : ViewModel() {\n\n    val settings: StateFlow&lt;AppSettings&gt; =\n        repository.settings.stateIn(\n            scope = viewModelScope,\n            started = SharingStarted.WhileSubscribed(5000),\n            initialValue = AppSettings()\n        )\n\n    fun setDarkMode(enabled: Boolean) {\n\n        viewModelScope.launch {\n            repository.setDarkMode(enabled)\n        }\n    }\n\n    fun setNotificationsEnabled(enabled: Boolean) {\n\n        viewModelScope.launch {\n            repository.setNotificationsEnabled(enabled)\n        }\n    }\n\n    fun setUserName(name: String) {\n\n        viewModelScope.launch {\n            repository.setUserName(name)\n        }\n    }\n\n    fun setFontSize(size: Int) {\n\n        viewModelScope.launch {\n            repository.setFontSize(size)\n        }\n    }\n\n    fun completeOnboarding() {\n\n        viewModelScope.launch {\n            repository.setOnboardingCompleted(true)\n        }\n    }\n\n    fun resetSettings() {\n\n        viewModelScope.launch {\n            repository.resetSettings()\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 converts the repository Flow into StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It exposes functions for updating preferences.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This example uses AppSettings() as its initial state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A production application may introduce an explicit loading state to avoid briefly displaying default settings before persisted preferences are loaded.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Step 9 \u2014 Create SettingsScreen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">File: presentation\/SettingsScreen.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings.presentation\n\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.rememberScrollState\nimport androidx.compose.foundation.verticalScroll\n\nimport androidx.compose.material3.*\n\nimport androidx.compose.runtime.Composable\nimport androidx.compose.runtime.getValue\n\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.unit.dp\n\nimport androidx.lifecycle.compose.collectAsStateWithLifecycle\n\n@OptIn(ExperimentalMaterial3Api::class)\n@Composable\nfun SettingsScreen(\n    viewModel: SettingsViewModel\n) {\n\n    val settings by viewModel.settings\n        .collectAsStateWithLifecycle()\n\n    Scaffold(\n        topBar = {\n\n            TopAppBar(\n                title = {\n                    Text(\"App Settings\")\n                }\n            )\n        }\n    ) { paddingValues -&gt;\n\n        Column(\n            modifier = Modifier\n                .fillMaxSize()\n                .padding(paddingValues)\n                .verticalScroll(rememberScrollState())\n                .padding(20.dp),\n            verticalArrangement =\n                Arrangement.spacedBy(20.dp)\n        ) {\n\n            Text(\n                text = \"Appearance\",\n                style = MaterialTheme.typography.titleLarge\n            )\n\n            Row(\n                modifier = Modifier.fillMaxWidth(),\n                horizontalArrangement =\n                    Arrangement.SpaceBetween\n            ) {\n\n                Text(\"Dark Mode\")\n\n                Switch(\n                    checked = settings.darkMode,\n                    onCheckedChange =\n                        viewModel::setDarkMode\n                )\n            }\n\n            HorizontalDivider()\n\n            Text(\n                text = \"Notifications\",\n                style = MaterialTheme.typography.titleLarge\n            )\n\n            Row(\n                modifier = Modifier.fillMaxWidth(),\n                horizontalArrangement =\n                    Arrangement.SpaceBetween\n            ) {\n\n                Text(\"Enable Notifications\")\n\n                Switch(\n                    checked = settings.notificationsEnabled,\n                    onCheckedChange =\n                        viewModel::setNotificationsEnabled\n                )\n            }\n\n            HorizontalDivider()\n\n            Text(\n                text = \"Profile\",\n                style = MaterialTheme.typography.titleLarge\n            )\n\n            OutlinedTextField(\n                value = settings.userName,\n                onValueChange = viewModel::setUserName,\n                label = {\n                    Text(\"User Name\")\n                },\n                modifier = Modifier.fillMaxWidth()\n            )\n\n            HorizontalDivider()\n\n            Text(\n                text = \"Font Size: ${settings.fontSize}\"\n            )\n\n            Slider(\n                value = settings.fontSize.toFloat(),\n                onValueChange = {\n                    viewModel.setFontSize(\n                        it.toInt()\n                    )\n                },\n                valueRange = 12f..24f,\n                steps = 11\n            )\n\n            HorizontalDivider()\n\n            Text(\n                text = if (settings.onboardingCompleted) {\n                    \"Onboarding Completed\"\n                } else {\n                    \"Onboarding Not Completed\"\n                }\n            )\n\n            Button(\n                onClick = viewModel::completeOnboarding,\n                modifier = Modifier.fillMaxWidth()\n            ) {\n\n                Text(\"Complete Onboarding\")\n            }\n\n            OutlinedButton(\n                onClick = viewModel::resetSettings,\n                modifier = Modifier.fillMaxWidth()\n            ) {\n\n                Text(\"Reset Settings\")\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 screen displays preferences from StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a user changes a setting:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>The UI calls the ViewModel.<\/li>\n\n\n\n<li>The ViewModel updates the repository.<\/li>\n\n\n\n<li>DataStore persists the new value.<\/li>\n\n\n\n<li>DataStore emits updated preferences.<\/li>\n\n\n\n<li>StateFlow updates.<\/li>\n\n\n\n<li>Compose recomposes the affected UI.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Production Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For text fields and sliders, avoid writing to DataStore on every keystroke or drag movement when unnecessary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Consider keeping temporary editing state and saving on focus loss, confirmation, or after a debounce.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Step 10 \u2014 Apply the Stored Theme<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To make dark mode affect the entire application, observe the preference above the screen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">File: MainActivity.kt<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example.datastoresettings\n\nimport android.os.Bundle\n\nimport androidx.activity.ComponentActivity\nimport androidx.activity.compose.setContent\n\nimport androidx.compose.material3.MaterialTheme\nimport androidx.compose.material3.darkColorScheme\nimport androidx.compose.material3.lightColorScheme\n\nimport androidx.lifecycle.compose.collectAsStateWithLifecycle\nimport androidx.lifecycle.viewmodel.compose.viewModel\n\nimport com.example.datastoresettings.presentation.SettingsScreen\nimport com.example.datastoresettings.presentation.SettingsViewModel\n\nimport dagger.hilt.android.AndroidEntryPoint\n\n@AndroidEntryPoint\nclass MainActivity : ComponentActivity() {\n\n    override fun onCreate(\n        savedInstanceState: Bundle?\n    ) {\n\n        super.onCreate(savedInstanceState)\n\n        setContent {\n\n            val settingsViewModel: SettingsViewModel =\n                viewModel()\n\n            val settings by settingsViewModel.settings\n                .collectAsStateWithLifecycle()\n\n            MaterialTheme(\n                colorScheme = if (settings.darkMode) {\n                    darkColorScheme()\n                } else {\n                    lightColorScheme()\n                }\n            ) {\n\n                SettingsScreen(\n                    viewModel = settingsViewModel\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 entire Compose UI reacts when dark mode changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The preference remains stored after the application closes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For a production application, consider a three-state theme setting:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Follow System<\/li>\n\n\n\n<li>Light<\/li>\n\n\n\n<li>Dark<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Also consider an initial loading state to prevent a theme flash during startup.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Expected Application UI<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|          App Settings          |\n|                                |\n| Appearance                     |\n|                                |\n| Dark Mode                &#91;ON]  |\n|                                |\n| ------------------------------ |\n|                                |\n| Notifications                  |\n|                                |\n| Enable Notifications     &#91;ON]  |\n|                                |\n| ------------------------------ |\n|                                |\n| Profile                        |\n|                                |\n| &#91; User Name                 ]  |\n|                                |\n| ------------------------------ |\n|                                |\n| Font Size: 16                  |\n|                                |\n| &#91;-------\u25cf----------------]     |\n|                                |\n| ------------------------------ |\n|                                |\n| Onboarding Not Completed       |\n|                                |\n|    &#91; Complete Onboarding ]     |\n|                                |\n|       &#91; Reset Settings ]       |\n|                                |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">All settings persist through DataStore.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">Advanced DataStore: Proto DataStore<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Preferences DataStore is ideal for simple key-value settings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For structured and strongly typed settings, Proto DataStore is another option.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. What Is Proto DataStore?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Proto DataStore stores structured objects using Protocol Buffers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Unlike Preferences DataStore, it requires a predefined schema.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Strongly typed data<\/li>\n\n\n\n<li>Defined schema<\/li>\n\n\n\n<li>Generated model classes<\/li>\n\n\n\n<li>Structured settings<\/li>\n\n\n\n<li>Better organization for complex preferences<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example Use Cases<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>User configuration<\/li>\n\n\n\n<li>Application preferences<\/li>\n\n\n\n<li>Feature settings<\/li>\n\n\n\n<li>Structured onboarding configuration<\/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\">24. Preferences DataStore vs Proto DataStore<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>Preferences DataStore<\/th><th>Proto DataStore<\/th><\/tr><tr><td>Storage model<\/td><td>Key-value pairs<\/td><td>Typed objects<\/td><\/tr><tr><td>Schema required<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Protocol Buffers<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Generated classes<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Best for<\/td><td>Simple settings<\/td><td>Structured settings<\/td><\/tr><tr><td>Flow support<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><tr><td>Transactional updates<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Preferences DataStore when settings are simple.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use Proto DataStore when a structured schema provides meaningful benefits.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. Add Proto DataStore Dependencies<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    implementation(\n        \"androidx.datastore:datastore:&lt;datastore-version&gt;\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You also need the Protocol Buffers Gradle plugin and a compatible protobuf runtime.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a lightweight Android application, protobuf-javalite is commonly used.<\/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 a Proto Schema<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>app\/src\/main\/proto\/user_settings.proto<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Add:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>syntax = \"proto3\";\n\noption java_package =\n    \"com.example.datastoresettings.proto\";\n\noption java_multiple_files = true;\n\nmessage UserSettings {\n\n    bool dark_mode = 1;\n\n    bool notifications_enabled = 2;\n\n    string user_name = 3;\n\n    int32 font_size = 4;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The schema defines the structure of the stored object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Protocol Buffers compiler generates Kotlin-compatible Java classes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Protocol Buffers default values differ from custom application defaults.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a missing boolean field defaults to false.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If your application requires notifications enabled by default, account for that in your serializer, schema design, or initialization strategy.<\/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 Proto Serializer<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Proto DataStore requires a Serializer.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>object UserSettingsSerializer :\n    Serializer&lt;UserSettings&gt; {\n\n    override val defaultValue: UserSettings =\n        UserSettings.getDefaultInstance()\n\n    override suspend fun readFrom(\n        input: InputStream\n    ): UserSettings {\n\n        return try {\n\n            UserSettings.parseFrom(input)\n\n        } catch (exception: InvalidProtocolBufferException) {\n\n            throw CorruptionException(\n                \"Cannot read user settings\",\n                exception\n            )\n        }\n    }\n\n    override suspend fun writeTo(\n        t: UserSettings,\n        output: OutputStream\n    ) {\n\n        t.writeTo(output)\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 serializer converts the stored Protocol Buffers data into UserSettings objects and writes updated objects back to storage.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. Create Proto DataStore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Declare the Proto DataStore delegate:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val Context.userSettingsDataStore:\n    DataStore&lt;UserSettings&gt; by dataStore(\n        fileName = \"user_settings.pb\",\n        serializer = UserSettingsSerializer\n    )<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a single DataStore instance per file within the same process.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Preferences DataStore and Proto DataStore should use separate storage files.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Reading Proto DataStore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Proto DataStore exposes a Flow of typed objects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val settingsFlow: Flow&lt;UserSettings&gt; =\n    context.userSettingsDataStore.data<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To extract a specific field:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val darkModeFlow =\n    context.userSettingsDataStore.data.map {\n        it.darkMode\n    }<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. Updating Proto DataStore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use updateData().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun setDarkMode(\n    enabled: Boolean\n) {\n\n    context.userSettingsDataStore.updateData {\n        currentSettings -&gt;\n\n        currentSettings.toBuilder()\n            .setDarkMode(enabled)\n            .build()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">updateData() performs a transactional update.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The transformation receives the current object and returns the updated object.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">31. Migrating from SharedPreferences<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Existing applications may already store settings in SharedPreferences.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore provides migration support.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val Context.dataStore by preferencesDataStore(\n    name = \"app_settings\",\n    produceMigrations = { context -&gt;\n\n        listOf(\n            SharedPreferencesMigration(\n                context,\n                \"legacy_settings\"\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 migration reads values from the existing SharedPreferences file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The migration configuration must be associated with the DataStore instance from the beginning.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not declare a second DataStore delegate for the same file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For an existing application, integrate the migration into the original delegate declaration.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">32. Handling DataStore Errors<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore reads can fail because of I\/O problems or data corruption.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val settingsFlow =\n    context.appDataStore.data\n        .catch { exception -&gt;\n\n            if (exception is IOException) {\n\n                emit(emptyPreferences())\n\n            } else {\n\n                throw 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\">IOException can be handled by emitting fallback preferences.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Unexpected exceptions should generally propagate rather than being silently ignored.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In production:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Log failures<\/li>\n\n\n\n<li>Avoid hiding persistent storage problems<\/li>\n\n\n\n<li>Show appropriate recovery UI<\/li>\n\n\n\n<li>Use corruption handlers only when data loss or reset is an acceptable recovery policy<\/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. DataStore and StateFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore works naturally with StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val settings = repository.settings\n    .stateIn(\n        scope = viewModelScope,\n        started = SharingStarted.WhileSubscribed(5000),\n        initialValue = AppSettings()\n    )<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">stateIn() converts a Flow into a StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow provides the latest value to Compose collectors.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">34. DataStore and Jetpack Compose<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Compose can collect DataStore-backed StateFlow using:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val settings by viewModel.settings\n    .collectAsStateWithLifecycle()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Lifecycle-aware collection<\/li>\n\n\n\n<li>Automatic UI updates<\/li>\n\n\n\n<li>Reduced manual observer management<\/li>\n\n\n\n<li>Unidirectional data flow<\/li>\n\n\n\n<li>Separation between storage and presentation<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Collect DataStore through a ViewModel or repository rather than directly coupling every composable to Context and storage APIs.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">35. DataStore Performance Best Practices<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Avoid Multiple Instances<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use one DataStore instance per file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Avoid Excessive Writes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not write preferences unnecessarily.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Keep Data Small<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore is designed for small settings, not large datasets.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Use Flow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Observe stored data reactively.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Avoid Blocking Reads<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use runBlocking on the main thread to retrieve settings during normal UI operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Keep Business Logic Separate<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use repositories or use cases to encapsulate storage operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Use Room for Complex Data<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not store large collections of relational records in DataStore.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">36. Testing Preferences DataStore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore repositories can be tested with temporary storage files.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Test Scenarios<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Default settings<\/li>\n\n\n\n<li>Dark mode enabled<\/li>\n\n\n\n<li>Notifications disabled<\/li>\n\n\n\n<li>Username updated<\/li>\n\n\n\n<li>Font size updated<\/li>\n\n\n\n<li>Onboarding completed<\/li>\n\n\n\n<li>Reset settings<\/li>\n\n\n\n<li>Persistence across DataStore recreation<\/li>\n\n\n\n<li>Read failure handling<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Example Test Logic<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun darkModePreferenceIsPersisted() = runTest {\n\n    repository.setDarkMode(true)\n\n    val settings =\n        repository.settings.first()\n\n    assertTrue(settings.darkMode)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test must initialize a repository with an isolated test DataStore instance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid sharing production preference files between tests.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">37. Testing Proto DataStore<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Proto DataStore tests should verify:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Default schema values<\/li>\n\n\n\n<li>Reading stored objects<\/li>\n\n\n\n<li>Updating individual fields<\/li>\n\n\n\n<li>Preserving unrelated fields<\/li>\n\n\n\n<li>Handling malformed data<\/li>\n\n\n\n<li>Schema compatibility<\/li>\n\n\n\n<li>Persistence across instances<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use temporary files and deterministic coroutine test scopes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">38. Common DataStore Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Creating Multiple DataStore Instances<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid multiple active instances for the same file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Using DataStore for Large Datasets<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Room for large or relational data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Blocking the Main Thread<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer asynchronous Flow and suspend APIs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Ignoring Read Errors<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Handle expected I\/O errors and surface persistent failures appropriately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Writing on Every UI Event<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Debounce or batch writes when appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Mixing Storage Logic with UI<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a repository layer.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Using Incorrect Default Values<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Define sensible defaults consistently.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Forgetting Migration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Migrate existing SharedPreferences values when upgrading an established app.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Storing Secrets as Plain Preferences<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore does not automatically encrypt values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use an appropriate security architecture for sensitive data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Ignoring Initial Loading State<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid showing incorrect settings while persisted values are loading.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">39. Production 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>Prefer DataStore for small persistent settings.<\/li>\n\n\n\n<li>Use Preferences DataStore for simple key-value storage.<\/li>\n\n\n\n<li>Use Proto DataStore for structured typed settings.<\/li>\n\n\n\n<li>Maintain one DataStore instance per file.<\/li>\n\n\n\n<li>Expose settings through Flow.<\/li>\n\n\n\n<li>Use Repository Pattern.<\/li>\n\n\n\n<li>Integrate Hilt for dependency injection.<\/li>\n\n\n\n<li>Convert Flow to StateFlow in ViewModel when appropriate.<\/li>\n\n\n\n<li>Use collectAsStateWithLifecycle() in Compose.<\/li>\n\n\n\n<li>Handle read and write errors.<\/li>\n\n\n\n<li>Avoid unnecessary writes.<\/li>\n\n\n\n<li>Use meaningful default values.<\/li>\n\n\n\n<li>Support SharedPreferences migration.<\/li>\n\n\n\n<li>Test persistence and reset behavior.<\/li>\n\n\n\n<li>Keep sensitive information out of unencrypted storage.<\/li>\n\n\n\n<li>Use Room for complex datasets.<\/li>\n\n\n\n<li>Keep UI state immutable.<\/li>\n\n\n\n<li>Support lifecycle-aware collection.<\/li>\n\n\n\n<li>Design settings screens for both light and dark themes.<\/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\">40. DataStore Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>API \/ Component<\/th><th>Purpose<\/th><\/tr><tr><td>Preferences DataStore<\/td><td>Key-value persistent storage<\/td><\/tr><tr><td>Proto DataStore<\/td><td>Structured typed storage<\/td><\/tr><tr><td>preferencesDataStore()<\/td><td>Creates Preferences DataStore delegate<\/td><\/tr><tr><td>dataStore()<\/td><td>Creates typed DataStore delegate<\/td><\/tr><tr><td>booleanPreferencesKey()<\/td><td>Boolean preference key<\/td><\/tr><tr><td>stringPreferencesKey()<\/td><td>String preference key<\/td><\/tr><tr><td>intPreferencesKey()<\/td><td>Integer preference key<\/td><\/tr><tr><td>DataStore.data<\/td><td>Reactive Flow of stored data<\/td><\/tr><tr><td>edit()<\/td><td>Transactional Preferences update<\/td><\/tr><tr><td>updateData()<\/td><td>Transactional typed DataStore update<\/td><\/tr><tr><td>Flow.map()<\/td><td>Transforms stored data<\/td><\/tr><tr><td>Flow.catch()<\/td><td>Handles read errors<\/td><\/tr><tr><td>stateIn()<\/td><td>Converts Flow to StateFlow<\/td><\/tr><tr><td>collectAsStateWithLifecycle()<\/td><td>Lifecycle-aware Compose collection<\/td><\/tr><tr><td>SharedPreferencesMigration<\/td><td>Migrates legacy preferences<\/td><\/tr><tr><td>Serializer<\/td><td>Reads and writes Proto objects<\/td><\/tr><tr><td>CorruptionException<\/td><td>Represents corrupted serialized data<\/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\">41. Practical Exercises<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Dark Mode<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store a Boolean dark mode preference.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Notifications<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a persistent notification toggle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: Username<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store a user-entered display name.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: Font Size<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Persist a selected font size.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: Onboarding<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Save onboarding completion state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Reset Settings<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Clear stored preferences.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: Hilt Integration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Inject SettingsRepository into ViewModel.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: StateFlow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Convert the settings Flow into StateFlow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: Proto DataStore<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a typed UserSettings schema.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Migration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Migrate preferences from SharedPreferences to DataStore.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">42. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is DataStore in Android?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore is an Android Jetpack library for asynchronous persistent storage of small amounts of data.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Preferences DataStore?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Preferences DataStore stores typed key-value preferences without requiring a schema.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Proto DataStore?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Proto DataStore stores structured, strongly typed objects using Protocol Buffers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is DataStore better than SharedPreferences?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For new Kotlin-based applications, DataStore is generally preferable because it supports coroutines, Flow, and transactional updates.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does DataStore support Jetpack Compose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. DataStore integrates naturally with Flow, ViewModel, StateFlow, and Compose.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can DataStore store dark mode preferences?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Dark mode is a common DataStore use case.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does DataStore support Hilt?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. A DataStore instance or repository can be provided through Hilt.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can DataStore replace Room?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Room is more suitable for relational data and complex queries.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does DataStore support migration?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. DataStore supports migration from SharedPreferences.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does DataStore automatically encrypt data?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. DataStore does not automatically provide encryption.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can DataStore store large files?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Use files, Room, or another suitable storage mechanism.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is DataStore suitable for production?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. DataStore is designed for persistent application settings and small structured data.<\/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>DataStore fundamentals<\/li>\n\n\n\n<li>SharedPreferences vs DataStore<\/li>\n\n\n\n<li>Preferences DataStore<\/li>\n\n\n\n<li>Proto DataStore<\/li>\n\n\n\n<li>Kotlin Flow integration<\/li>\n\n\n\n<li>Reading and writing preferences<\/li>\n\n\n\n<li>Preference keys<\/li>\n\n\n\n<li>Repository Pattern<\/li>\n\n\n\n<li>Hilt integration<\/li>\n\n\n\n<li>MVVM architecture<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>Jetpack Compose settings UI<\/li>\n\n\n\n<li>Dark mode persistence<\/li>\n\n\n\n<li>Notification preferences<\/li>\n\n\n\n<li>Username storage<\/li>\n\n\n\n<li>Font size preferences<\/li>\n\n\n\n<li>Onboarding state<\/li>\n\n\n\n<li>Reset settings<\/li>\n\n\n\n<li>Protocol Buffers schema<\/li>\n\n\n\n<li>Proto serializer<\/li>\n\n\n\n<li>SharedPreferences migration<\/li>\n\n\n\n<li>Error handling<\/li>\n\n\n\n<li>Testing<\/li>\n\n\n\n<li>Performance optimization<\/li>\n\n\n\n<li>Production best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">DataStore provides a modern foundation for managing persistent application preferences in Android.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining DataStore with Kotlin, Flow, Hilt, ViewModel, and Jetpack Compose, developers can build reactive, maintainable, and lifecycle-aware settings screens.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key principle is simple:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Use DataStore for small persistent settings, expose values through Flow, and keep storage logic separate from the user interface.<\/strong><\/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 51 \u2014 Android App Startup Optimization with Kotlin &amp; Jetpack Compose: Baseline Profiles, Lazy Initialization &amp; Performance<\/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>Android app startup fundamentals<\/li>\n\n\n\n<li>Cold, warm, and hot startup<\/li>\n\n\n\n<li>Time to Initial Display<\/li>\n\n\n\n<li>Time to Full Display<\/li>\n\n\n\n<li>Measuring startup performance<\/li>\n\n\n\n<li>Macrobenchmark<\/li>\n\n\n\n<li>Baseline Profiles<\/li>\n\n\n\n<li>Startup Profiles<\/li>\n\n\n\n<li>Lazy initialization<\/li>\n\n\n\n<li>Dependency initialization optimization<\/li>\n\n\n\n<li>Jetpack App Startup<\/li>\n\n\n\n<li>Main-thread performance<\/li>\n\n\n\n<li>Compose startup optimization<\/li>\n\n\n\n<li>Production profiling and best practices<\/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","protected":false},"excerpt":{"rendered":"<p>Master Jetpack DataStore in Android with Kotlin and Jetpack Compose. Learn Preferences DataStore, Proto DataStore, Kotlin Flow, SharedPreferences migration, Hilt integration, and build a reactive Settings Manager app.<\/p>\n","protected":false},"author":1,"featured_media":213,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":2,"footnotes":""},"categories":[3,333,17],"tags":[],"class_list":["post-210","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-development","category-android-tutorials","category-data-storage"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/210","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=210"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/210\/revisions"}],"predecessor-version":[{"id":211,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/210\/revisions\/211"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/213"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=210"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=210"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=210"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}