【Jetpack 内核实战 07 】:DataStore——替代 SharedPreferences 的现代化存储

1 阅读14分钟

DataStore——替代 SharedPreferences 的现代化存储

各位 Android 开发者好,欢迎来到《Jetpack 内核实战》系列第 7 篇。 在上一篇中,我们完成了 Room 进阶能力的升级,实现了结构化数据的响应式持久化与版本无损迁移。但在轻量级配置存储场景(如主题设置、用户偏好、开关状态),传统的 SharedPreferences 依然存在性能差、ANR 风险高、类型不安全等诸多问题。 本篇我们引入 Jetpack 架构的轻量存储组件——DataStore。它是 Google 官方推出的 SharedPreferences 替代方案,基于 Kotlin 协程与 Flow 实现,兼具异步安全、类型可靠、原子操作等优势。本文将从 SP 痛点分析、两种 DataStore 对比、核心 API 讲解、设置页实战、SP 迁移全流程展开,所有代码遵循分层架构规范,可直接编译落地。

一、SharedPreferences 的核心痛点:为什么必须替换?

SharedPreferences 是 Android 元老级的轻量存储方案,但设计缺陷明显,在现代 Android 开发中已经成为性能与稳定性的重灾区。

1. 主线程阻塞与 ANR 风险

这是 SP 最致命的问题:

  • commit() 是同步写入,直接在调用线程执行磁盘 IO,主线程调用会阻塞界面,极易引发 ANR
  • apply() 虽然是异步写入,但在 Activity 跳转、页面销毁等生命周期节点,系统会等待 SP 写入完成,依然可能阻塞主线程,触发 ANR
  • 数据量越大、SP 文件越多,ANR 概率越高。线上统计中,SP 导致的 ANR 始终占比居高不下

2. 类型不安全,无编译校验

SP 以 key-value 形式存储,读写全靠字符串 key 匹配,没有编译时类型校验:

  • 存的是 Int,用 String 去读,运行时直接崩溃

  • key 拼写错误,不会提前报错,只会返回默认值,排查困难

  • 多人协作场景下,key 命名混乱、类型错用问题频发

3. 不支持异步与响应式

SP 本质是同步读写,原生不支持协程,无法返回 Flow/LiveData 实现响应式更新。数据变化需要手动监听,开发体验差。

4. 无事务保障,原子性差

SP 每次修改都是全量写入文件,多次 edit 会导致多次 IO;并发写入场景下容易出现数据丢失,无法保证原子性。同时不支持增量更新,每次修改都要把整个 XML 文件重新写入磁盘,性能随数据量增大急剧下降。

5. 不支持结构化数据

SP 只能存储基础类型(Int、String、Boolean 等),无法存储自定义对象、集合等结构化数据,复杂场景只能手动序列化,代码冗余且易出错。

DataStore 的出现,正是为了系统性解决以上所有痛点,成为 Android 轻量存储的官方标准方案。

二、DataStore 概述:两种实现方案对比

DataStore 是基于 Kotlin 协程与 Flow 的轻量持久化组件,提供了两种不同的实现方式,分别适配不同的业务场景。

1. 两种 DataStore 核心差异

对比维度Preferences DataStoreProto DataStore
存储方式键值对存储,类似 SP结构化对象存储,基于 Protocol Buffers
类型安全无编译时校验,靠 key 匹配强类型,编译时校验 schema,类型完全安全
适用场景简单配置、开关状态、少量键值对复杂结构化配置、多字段的用户偏好
学习成本极低,和 SP 用法接近较高,需要定义 proto schema 并生成代码
响应式支持原生支持 Flow,数据变化自动通知原生支持 Flow,整体对象更新

2. DataStore 通用核心优势

优势说明
完全异步,无 ANR 风险所有读写操作基于协程在后台线程执行,不会阻塞主线程
原生响应式数据以 Flow 形式暴露,数据变化自动发射新值
原子性与事务保障写入操作是原子的,支持事务式批量修改,并发场景安全
异常处理完善读写异常可通过 Flow 的 catch 操作符捕获,不会直接崩溃
支持迁移官方提供 SharedPreferencesMigration,可无缝从 SP 迁移

3. 选型建议

场景推荐方案
简单的轻量配置、少量开关、替代原有 SPPreferences DataStore,上手快,改造成本低
配置结构复杂、字段多、对类型安全要求高Proto DataStore,长期可维护性更好

本专栏以 Preferences DataStore 为核心实战内容,重点讲解替代 SP 的标准落地流程。

三、Preferences DataStore 核心 API 详解

1. 依赖配置

在 gradle/libs.versions.toml 中添加 DataStore 版本:

[versions]
datastore = "1.0.0"

[libraries]
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }

在模块级 app/build.gradle.kts 中添加依赖:

dependencies {
    implementation(libs.androidx.datastore.preferences)
}

2. 核心 Key 定义

和 SP 类似,DataStore 通过 Key 标识存储项,但 DataStore 的 Key 自带类型信息,读写类型严格匹配:

package com.example.jetpacknote.data.datastore

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

object SettingsKeys {
    // 夜间模式开关
    val KEY_NIGHT_MODE = booleanPreferencesKey("night_mode")
    
    // 字体大小,单位 sp
    val KEY_FONT_SIZE = intPreferencesKey("font_size")
    
    // 用户名称
    val KEY_USER_NAME = stringPreferencesKey("user_name")
}

支持的类型:booleanPreferencesKey、intPreferencesKey、longPreferencesKey、floatPreferencesKey、stringPreferencesKey、stringSetPreferencesKey,覆盖 SP 全部支持的类型。

3. 创建 DataStore 实例

使用 preferencesDataStore 委托创建 DataStore 实例。必须在顶层定义,且在整个应用生命周期内保持单例。

package com.example.jetpacknote.data

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

// Context 扩展属性,全局唯一 DataStore 实例
// 文件名:settings_pref,会生成 settings_pref.preferences_pb 文件
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = "settings_pref"
)

4. 读取数据:data Flow 属性

DataStore 暴露一个 data 属性,类型是 Flow。每次数据发生变化,Flow 自动发射最新的 Preferences 对象:

class SettingsRepository private constructor(private val context: Context) {

    // 夜间模式状态流
    val nightModeFlow: Flow<Boolean> = context.dataStore.data
        .catch { exception ->
            // 捕获读取异常,比如文件损坏,返回默认值
            if (exception is IOException) {
                emit(emptyPreferences())
            } else {
                throw exception
            }
        }
        .map { preferences ->
            // 读取值,取不到则用默认值 false
            preferences[SettingsKeys.KEY_NIGHT_MODE] ?: false
        }

    // 字体大小流,默认 16sp
    val fontSizeFlow: Flow<Int> = context.dataStore.data
        .catch { emit(emptyPreferences()) }
        .map { preferences ->
            preferences[SettingsKeys.KEY_FONT_SIZE] ?: 16
        }
}

异常处理要点:dataStore.data 读取文件时可能抛出 IOException,使用 .catch {} 捕获并发射默认值,避免 Flow 终止。

5. 写入数据:edit 挂起函数

写入数据通过 edit() 挂起函数实现,内部是事务式操作,lambda 内的所有修改会原子性地提交:

class SettingsRepository private constructor(private val context: Context) {

    // 设置夜间模式
    suspend fun setNightMode(isNight: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[SettingsKeys.KEY_NIGHT_MODE] = isNight
        }
    }

    // 设置字体大小
    suspend fun setFontSize(size: Int) {
        context.dataStore.edit { preferences ->
            preferences[SettingsKeys.KEY_FONT_SIZE] = size
        }
    }

    // 批量更新(原子性:要么全部成功,要么全部失败)
    suspend fun updateSettings(nightMode: Boolean, fontSize: Int) {
        context.dataStore.edit { preferences ->
            preferences[SettingsKeys.KEY_NIGHT_MODE] = nightMode
            preferences[SettingsKeys.KEY_FONT_SIZE] = fontSize
        }
    }
}

注意:edit() 是 suspend 挂起函数,必须在协程中调用,自动在后台线程执行 IO 操作,不会阻塞主线程。

6. 线程安全与原子性保障

DataStore 的写入是单线程串行执行的,所有 edit 操作会按顺序排队执行,保证写入的原子性,不会出现并发写入导致的数据错乱。同时读取基于 Flow,支持多观察者并发读取,读写分离,线程安全由框架底层保证,开发者无需手动加锁。

四、Proto DataStore:强类型结构化存储(概览)

Preferences DataStore 解决了 SP 的性能问题,但依然是键值对模式,没有强类型保障。如果需要更严谨的结构化配置,就需要 Proto DataStore。

1. 核心原理

Proto DataStore 基于 Google 的 Protocol Buffers 序列化方案:

  1. 通过 .proto 文件定义数据结构 schema

  2. 编译时自动生成对应的 Kotlin 类

  3. 读写的是完整的结构化对象,而非零散的键值对

2. 核心优势

优势说明
强类型安全所有字段在 proto 文件中定义,编译时校验,不会出现类型错用
结构化存储支持嵌套对象、列表等复杂结构,适合多字段配置集
序列化性能高Protobuf 是二进制序列化,体积更小、读写速度比 XML/JSON 更快
可扩展性好后续新增字段可以向前兼容,不会导致旧数据失效

3. 适用场景

  • 用户偏好配置项多,需要统一管理的场景
  • 对类型安全要求高,避免线上键值错用崩溃的中大型项目
  • 配置结构复杂,存在嵌套、列表等结构化数据的场景

入门阶段优先掌握 Preferences DataStore 即可满足绝大多数业务需求,Proto DataStore 可以在项目架构升级时再引入。

五、实战落地:设置页开发

理论讲完,我们基于记事本项目,实现一个完整的设置页面:包含夜间模式开关、字体大小调节,所有配置通过 Preferences DataStore 持久化存储。

1. 封装 SettingsRepository(Data Layer)

遵循分层架构,把 DataStore 操作封装到 Repository 中,上层不直接接触 DataStore 实现:

package com.example.jetpacknote.data

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import com.example.jetpacknote.data.datastore.SettingsKeys
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException

// Context 扩展属性,全局唯一 DataStore 实例
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = "settings_pref"
)

class SettingsRepository private constructor(private val context: Context) {

    // 夜间模式状态流
    val nightModeFlow: Flow<Boolean> = context.dataStore.data
        .catch { exception ->
            if (exception is IOException) {
                emit(emptyPreferences())
            } else {
                throw exception
            }
        }
        .map { preferences ->
            preferences[SettingsKeys.KEY_NIGHT_MODE] ?: false
        }

    // 字体大小流,默认 16sp
    val fontSizeFlow: Flow<Int> = context.dataStore.data
        .catch { emit(emptyPreferences()) }
        .map { preferences ->
            preferences[SettingsKeys.KEY_FONT_SIZE] ?: 16
        }

    suspend fun setNightMode(isNight: Boolean) {
        context.dataStore.edit { preferences ->
            preferences[SettingsKeys.KEY_NIGHT_MODE] = isNight
        }
    }

    suspend fun setFontSize(size: Int) {
        context.dataStore.edit { preferences ->
            preferences[SettingsKeys.KEY_FONT_SIZE] = size.coerceIn(12, 24)
        }
    }

    companion object {
        @Volatile
        private var INSTANCE: SettingsRepository? = null

        fun getInstance(context: Context): SettingsRepository {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: SettingsRepository(context.applicationContext).also { INSTANCE = it }
            }
        }
    }
}

2. 创建设置页 ViewModel

package com.example.jetpacknote.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.jetpacknote.data.SettingsRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class SettingsViewModel(application: Application) : AndroidViewModel(application) {

    private val repository = SettingsRepository.getInstance(application)

    // 夜间模式状态,转为 StateFlow 保证状态唯一
    val nightMode: StateFlow<Boolean> = repository.nightModeFlow
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = false
        )

    // 字体大小状态
    val fontSize: StateFlow<Int> = repository.fontSizeFlow
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = 16
        )

    fun toggleNightMode() {
        viewModelScope.launch {
            repository.setNightMode(!nightMode.value)
        }
    }

    fun changeFontSize(size: Int) {
        viewModelScope.launch {
            repository.setFontSize(size)
        }
    }
}

3. 创建设置页布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp">

    <!-- 夜间模式设置 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="夜间模式"
            android:textSize="16sp" />

        <androidx.appcompat.widget.SwitchCompat
            android:id="@+id/switchNightMode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <!-- 字体大小设置 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="32dp">

        <TextView
            android:id="@+id/tvFontSize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="字体大小:16sp"
            android:textSize="16sp" />

        <SeekBar
            android:id="@+id/seekBarFont"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:max="12"
            android:progress="4"
            android:layout_marginTop="8dp" />
    </LinearLayout>

</LinearLayout>

4. SettingsActivity 实现

package com.example.jetpacknote

import android.os.Bundle
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModels
import com.example.jetpacknote.databinding.ActivitySettingsBinding
import com.example.jetpacknote.ui.SettingsViewModel
import kotlinx.coroutines.launch

class SettingsActivity : AppCompatActivity() {

    private val binding by lazy { ActivitySettingsBinding.inflate(layoutInflater) }
    private val viewModel: SettingsViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        initListeners()
        observeSettings()
    }

    private fun initListeners() {
        // 夜间模式开关
        binding.switchNightMode.setOnCheckedChangeListener { _, isChecked ->
            if (binding.switchNightMode.isPressed) {  // 避免初始值触发回调
                viewModel.toggleNightMode()
            }
        }

        // 字体大小拖动
        binding.seekBarFont.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    viewModel.changeFontSize(12 + progress)  // 12sp 起步,最大 24sp
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun observeSettings() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                // 监听夜间模式变化,实时切换主题
                launch {
                    viewModel.nightMode.collect { isNight ->
                        binding.switchNightMode.isChecked = isNight
                        val mode = if (isNight) {
                            AppCompatDelegate.MODE_NIGHT_YES
                        } else {
                            AppCompatDelegate.MODE_NIGHT_NO
                        }
                        AppCompatDelegate.setDefaultNightMode(mode)
                    }
                }

                // 监听字体大小变化,实时更新文本
                launch {
                    viewModel.fontSize.collect { size ->
                        binding.tvFontSize.text = "字体大小:${size}sp"
                        binding.tvFontSize.textSize = size.toFloat()
                        binding.seekBarFont.progress = size - 12
                    }
                }
            }
        }
    }
}

六、SP 迁移到 DataStore 实战

如果项目之前用 SharedPreferences 存储配置,DataStore 官方提供了 SharedPreferencesMigration 迁移工具,无需手动读写,一行配置即可完成自动迁移。

1. 基础迁移配置

修改 DataStore 创建代码,添加迁移配置:

import androidx.datastore.preferences.migrations.SharedPreferencesMigration

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = "settings_pref",
    produceMigrations = { context ->
        listOf(
            // 从 SP 迁移数据:传入旧 SP 的文件名
            SharedPreferencesMigration(
                context = context,
                sharedPreferencesName = "old_settings_pref"  // 旧 SP 文件名
            )
        )
    }
)

2. 迁移指定 Key

如果只想迁移部分 Key,可以传入第三个参数:

SharedPreferencesMigration(
    context = context,
    sharedPreferencesName = "old_settings_pref",
    keysToMigrate = setOf("night_mode", "font_size")  // 只迁移指定的 Key
)

3. 迁移流程说明

  • 执行时机:首次访问 DataStore 时自动执行
  • 执行方式:全程异步,在后台线程执行,不会阻塞主线程
  • 数据合并:如果 DataStore 中已存在相同的 Key,不会覆盖
  • 清理旧数据:迁移完成后,自动删除旧 SP 文件
  • 用户无感知:整个过程完全自动,无需用户任何操作

⚠️ 注意:迁移完成后旧 SP 文件会被删除。如果担心迁移失败,建议先在测试环境中验证。

七、FAQ / 避坑指南

Q1:DataStore 比 SharedPreferences 更安全的核心原因是什么?

A:核心体现在三个维度:

维度SharedPreferencesDataStore
线程安全❌ 并发写入易丢数据✅ 串行化操作,线程安全
事务原子性❌ 多键修改无事务保证✅ ACID 事务保证
错误反馈❌ apply() 无返回值✅ 协程异常机制可捕获
主线程阻塞❌ commit() 和 apply() 的 fsync() 会阻塞✅ 全程异步非阻塞
解析异常❌ 运行时崩溃✅ 可捕获处理

Q2:Preferences DataStore 不支持的类型怎么处理?

A:Preferences DataStore 仅支持基础类型,遇到自定义对象、List 等复杂类型有两种方案:

方案适用场景实现方式
序列化转字符串简单对象、小列表用 Gson/Moshi 将对象转为 JSON 字符串存储
切换 Proto DataStore复杂类型多、结构复杂用 Protocol Buffers 定义 Schema
// 方案一示例:序列化为 JSON
val userJson = Gson().toJson(user)
preferences[stringPreferencesKey("user")] = userJson

// 读取时反序列化
val user = Gson().fromJson(json, User::class.java)

注意:不要存大量数据或大对象,DataStore 定位是轻量配置存储,大量结构化数据请用 Room。

Q3:Proto DataStore 的适用场景是什么?

A:优先选择 Proto DataStore 的场景:

场景说明
配置项多超过 10 个以上,统一管理成结构化对象更清晰
结构复杂存在嵌套、列表等复杂形态,键值对难以维护
类型安全要求高需要编译时校验避免线上崩溃
团队协作Schema 统一管理,避免 key 命名混乱

简单配置、替代原有 SP 的场景,Preferences DataStore 足够用,无需强行引入 Proto。

Q4:DataStore 的 Flow 如何安全收集?

A:DataStore 的 data 属性返回的 Flow 是无限流,必须在 Activity/Fragment 中使用 repeatOnLifecycle 安全收集:

// ✅ 正确:只在 STARTED 状态收集
lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        dataStore.data.collect { preferences ->
            // 更新 UI
        }
    }
}

// ❌ 错误:页面在后台时仍在收集,浪费资源
lifecycleScope.launch {
    dataStore.data.collect { preferences ->
        // 页面在后台时仍在执行
    }
}

Q5:DataStore 读写操作会阻塞主线程吗?

A:不会。DataStore 所有操作默认在 Dispatchers.IO 执行:

  • 读取:dataStore.data 返回的 Flow 在 IO 线程执行
  • 写入:edit {} 在 IO 线程执行
  • UI 更新:通过 Flow 的 collect 自动切换到主线程

开发者不需要手动使用 withContext(Dispatchers.IO) 包裹 DataStore 操作。

Q6:DataStore 和 Room 如何选择?

A:两者定位完全不同:

对比维度DataStoreRoom
数据量小(KB 级别)大(MB/GB 级别)
数据结构键值对 / 简单对象关系型数据(多表、关联)
查询能力简单读取复杂 SQL 查询、索引、聚合
适用场景用户偏好、应用配置业务数据(笔记、用户、订单)

简单判断:需要 SELECT * FROM notes WHERE ... → 用 Room;只需要 getDarkMode() → 用 DataStore。

八、架构演进小结

至此,我们的完整数据层架构已经成型:

层级组件职责
UI 层Activity/Fragment + ViewModel界面渲染 + 状态管理
Domain 层Repository统一数据入口
Data 层Room结构化数据持久化(笔记)
Data 层DataStore轻量配置存储(主题、字体)
┌─────────────────────────────────────────────────────────┐
│                     UI Layer                           │
│    Activity/Fragment ←── observe ─── ViewModel         │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│                   Domain Layer                         │
│       SettingsRepository  /  NoteRepository            │
└─────────────────────────────────────────────────────────┘
                        │
          ┌─────────────┴─────────────┐
          ▼                           ▼
┌─────────────────┐         ┌─────────────────┐
│   DataStore     │         │     Room        │
│   (配置存储)     │         │   (业务数据)     │
│ - 夜间模式       │         │ - 笔记增删改查   │
│ - 字体大小       │         │ - 响应式查询     │
└─────────────────┘         └─────────────────┘

⚠️注意: 每期代码我都会提交更新到AtmoGit中

下篇预告

本篇我们系统掌握了 DataStore 的核心能力,完成了从 SharedPreferences 到 DataStore 的升级,实现了设置页的配置持久化,解决了轻量存储的 ANR 与类型安全痛点。

目前 Room 负责结构化数据、DataStore 负责轻量配置,两大持久化组件已经全部落地。下一篇我们将把两者深度整合,构建 DataStore + Room 的离线优先架构,实现多数据源统一管理、数据一致性保障,打造完整的离线可用应用架构。


🌟 点赞 + 收藏 + 关注,第一时间收到更新推送 💬 评论区聊聊:你的项目里有没有被 SharedPreferences 的 ANR 坑过?欢迎留言分享!