DataStore 库以异步、一致的事务方式存储数据,克服了 SharedPreferences 的一些缺点。本页重点介绍如何在 Kotlin Multiplatform (KMP) 项目中创建 DataStore。如需详细了解 DataStore,请参阅 DataStore 的主要文档和官方示例。
设置依赖项
如需在 KMP 项目中设置 DataStore,请在模块的 build.gradle.kts
文件中添加工件的依赖项:
commonMain.dependencies {
// DataStore library
implementation("androidx.datastore:datastore:1.1.7")
// The Preferences DataStore library
implementation("androidx.datastore:datastore-preferences:1.1.7")
}
定义 DataStore 类
您可以在共享 KMP 模块的公共源代码中使用 DataStoreFactory
定义 DataStore
类。将这些类放置在公共源代码中,可在所有目标平台之间共享这些类。您可以使用 actual
和 expect
声明创建平台专用实现。
创建 DataStore 实例
您需要定义如何在每个平台上实例化 DataStore 对象。由于文件系统 API 存在差异,因此这是 API 中唯一需要在特定平台源代码集中的部分。
常见
// shared/src/commonMain/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
如需在 Android 上创建 DataStore
实例,您需要 Context
和路径。
// shared/src/androidMain/kotlin/createDataStore.android.kt
fun createDataStore(context: Context): DataStore<Preferences> = createDataStore(
producePath = { context.filesDir.resolve(dataStoreFileName).absolutePath }
)
iOS
在 iOS 上,您可以从 NSDocumentDirectory
检索路径:
// shared/src/iosMain/kotlin/createDataStore.ios.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"
}
)
JVM(桌面设备)
如需在 JVM(桌面版)上创建 DataStore
实例,请使用 Java 或 Kotlin API 提供路径:
// shared/src/jvmMain/kotlin/createDataStore.desktop.kt
fun createDataStore(): DataStore<Preferences> = createDataStore(
producePath = {
val file = File(System.getProperty("java.io.tmpdir"), dataStoreFileName)
file.absolutePath
}
)