DataStore (Kotlin Multiplatform)

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 類別。將這些類別放在通用來源中,即可在所有目標平台上共用這些類別。您可以使用 actualexpect 宣告,建立特定平台的實作項目。

建立 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
    }
)