0Pricing
Android Academy · 课时

DataStore 偏好设置

使用现代化的 DataStore 库替代 SharedPreferences。将数据读取为 Kotlin Flow,使用 edit{} 写入,并安全地处理错误。

DataStore 偏好设置 是 CoddyKit 上的免费 Android Academy 课时。 这是第 5 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Android Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Android Academy 课程共包含 6 节课。

为什么使用 DataStore?

DataStore 是 SharedPreferences 的现代替代方案。它解决了实际开发中的问题:

  • SharedPreferences 会阻塞界面线程,而 DataStore 完全异步
  • SharedPreferences 可能抛出未捕获的异常,而 DataStore 通过 Flow 处理错误
  • DataStore 提供类型安全(Preferences)或架构安全(Proto)
  • 原生支持 Kotlin 协程和 Flow

DataStore 的两种类型

请根据您的使用场景选择合适的类型:

  • Preferences DataStore — 使用键值对,不需要架构。设置最简单,适合应用设置和用户偏好。
  • Proto DataStore — 使用 Protocol Buffers 保存类型化对象。需要一个 .proto 架构文件,适合结构化数据。

本课将介绍 Preferences DataStore。

添加依赖

将 DataStore 添加到 app/build.gradle:

// app/build.gradle
dependencies {
    implementation 'androidx.datastore:datastore-preferences:1.1.1'
    // Coroutines (likely already in your project)
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
}

创建 DataStore 实例

使用顶层委托创建一次 DataStore。通常会在独立文件中完成:

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore

// Top-level property — creates a single DataStore instance per Context
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefs")

定义键

键是类型安全的对象,而不是普通字符串。请使用正确的工厂函数创建它们:

import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey

object PreferencesKeys {
    val DARK_MODE    = booleanPreferencesKey("dark_mode")
    val USER_NAME    = stringPreferencesKey("user_name")
    val LAUNCH_COUNT = intPreferencesKey("launch_count")
}

写入数据

在协程中使用 edit { } 写入数据:

import androidx.datastore.preferences.core.edit

// In a ViewModel or Repository:
suspend fun saveDarkMode(enabled: Boolean) {
    context.dataStore.edit { prefs ->
        prefs[PreferencesKeys.DARK_MODE] = enabled
    }
}

suspend fun incrementLaunchCount() {
    context.dataStore.edit { prefs ->
        val current = prefs[PreferencesKeys.LAUNCH_COUNT] ?: 0
        prefs[PreferencesKeys.LAUNCH_COUNT] = current + 1
    }
}

使用 Flow 读取数据

DataStore 会以 Flow 的形式提供数据。使用 map 提取所需的值:

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

val darkModeFlow: Flow<Boolean> = context.dataStore.data
    .map { prefs ->
        prefs[PreferencesKeys.DARK_MODE] ?: false  // default = false
    }

val userNameFlow: Flow<String> = context.dataStore.data
    .map { prefs ->
        prefs[PreferencesKeys.USER_NAME] ?: "Guest"
    }

在 ViewModel 中收集数据

使用 stateIn 从 ViewModel 暴露 DataStore 的 Flow,以高效地收集数据:

class SettingsViewModel(private val repo: SettingsRepository) : ViewModel() {

    val isDarkMode: StateFlow<Boolean> = repo.darkModeFlow
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = false
        )

    fun toggleDarkMode(enabled: Boolean) {
        viewModelScope.launch {
            repo.saveDarkMode(enabled)
        }
    }
}

在 Activity/Fragment 中观察

使用 lifecycleScope.launch 在界面中收集 StateFlow:

// In Fragment:
lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.isDarkMode.collect { darkMode ->
            binding.switchDarkMode.isChecked = darkMode
            AppCompatDelegate.setDefaultNightMode(
                if (darkMode) AppCompatDelegate.MODE_NIGHT_YES
                else AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
            )
        }
    }
}

错误处理

如果文件损坏,DataStore 会发出 IOException。请在 Flow 流程中捕获它:

import kotlinx.coroutines.flow.catch
import java.io.IOException

val safeFlow: Flow<Boolean> = context.dataStore.data
    .catch { exception ->
        if (exception is IOException) {
            emit(emptyPreferences())   // return defaults
        } else {
            throw exception
        }
    }
    .map { prefs ->
        prefs[PreferencesKeys.DARK_MODE] ?: false
    }

DataStore 与 SharedPreferences

DataStore 更具优势的原因总结如下:

  • DataStore 会自动在后台线程上读写数据,不存在 ANR 风险
  • SharedPreferences 的 apply() 可能会静默失败;DataStore 会通过 Flow 传递错误
  • DataStore 具有响应式特性,数据变化时界面会自动更新
  • SharedPreferences 没有迁移方案;DataStore 内置了 SharedPreferencesMigration

快速检查

DataStore 使用什么主要机制将数据提供给应用的其他部分?

总结:DataStore Preferences

DataStore 是持久化简单数据的现代方式:

  • 添加 datastore-preferences 依赖
  • 使用 preferencesDataStore 委托创建单个实例
  • 使用 stringPreferencesKey、booleanPreferencesKey 等定义类型安全的键
  • 在协程中使用 dataStore.edit { } 写入数据
  • 使用 dataStore.data.map { } 以 Flow 的形式读取数据
  • 使用 .catch { emit(emptyPreferences()) } 处理 IOException

下一步:使用 DiffUtil 构建高效的列表适配器。

常见问题解答

「DataStore 偏好设置」课时是免费的吗?

是的 — 「DataStore 偏好设置」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Android Academy 课程的其余内容,请升级到 CoddyKit PRO。 Android Academy 课程共包含 6 节课。

「DataStore 偏好设置」这节课中我会学到什么?

使用现代化的 DataStore 库替代 SharedPreferences。将数据读取为 Kotlin Flow,使用 edit{} 写入,并安全地处理错误。 你通过在浏览器中直接运行的动手代码来练习 Android Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Android Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Android Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 5 节课,共 6 节。

「DataStore 偏好设置」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Android Academy 课中编写并运行代码吗?

能。每节 Android Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Kotlin 集合
  2. RecyclerView 基础
  3. RecyclerView 点击事件
  4. SharedPreferences
  5. DataStore 偏好设置
  6. 适配器与 DiffUtil
← 返回 Android Academy