DataStore 库以异步、一致且事务性的方式存储数据,克服了 SharedPreferences 的一些缺点。本页面重点介绍如何在 Kotlin Multiplatform (KMP) 项目中创建 DataStore。有关 DataStore 的更多信息,请参阅 DataStore 主要文档和官方示例。
设置依赖项
DataStore 在 1.1.0 及更高版本中支持 KMP。
要在 KMP 项目中设置 DataStore,请在模块的 build.gradle.kts
文件中添加 artifact 的依赖项。
androidx.datastore:datastore
- DataStore 库androidx.datastore:datastore-preferences
- Preferences DataStore 库
定义 DataStore 类
您可以在共享 KMP 模块的公共源中通过 DataStoreFactory
定义 DataStore
类。将这些类放在公共源中,它们就可以在所有目标平台之间共享。您可以使用 actual
和 expect
声明来创建平台特定的实现。
创建 DataStore 实例
您需要定义如何在每个平台上实例化 DataStore 对象。由于文件系统 API 的差异,这是 API 中唯一需要位于特定平台源集的部分。
通用
// shared/src/androidMain/kotlin/createDataStore.kt
/**
* Gets the singleton DataStore instance, creating it if necessary.
*/
fun createDataStore(producePath: () -> String): DataStore<Preferences> =
PreferenceDataStoreFactory.createWithPath(
produceFile = { producePath().toPath() }
)
internal const val dataStoreFileName = "dice.preferences_pb"
Android
要创建 DataStore
实例,您需要一个 Context
以及文件路径。
// shared/src/androidMain/kotlin/createDataStore.android.kt
fun createDataStore(context: Context): DataStore<Preferences> = createDataStore(
producePath = { context.filesDir.resolve(dataStoreFileName).absolutePath }
)
iOS
要创建 DataStore 实例,您需要一个 DataStore 工厂以及 DataStore 路径。
// shared/src/iosMain/kotlin/createDataStore.kt
fun createDataStore(): DataStore<Preferences> = createDataStore(
producePath = {
val documentDirectory: NSURL? = NSFileManager.defaultManager.URLForDirectory(
directory = NSDocumentDirectory,
inDomain = NSUserDomainMask,
appropriateForURL = null,
create = false,
error = null,
)
requireNotNull(documentDirectory).path + "/$dataStoreFileName"
}
)