DataStore (Kotlin Multiplatform)

DataStore 程式庫會以非同步、一致且交易式的方式儲存資料,克服 SharedPreferences 的某些缺點。本頁主要說明如何在 Kotlin Multiplatform (KMP) 專案中建立 DataStore。如要進一步瞭解 DataStore,請參閱 DataStore 的主要說明文件官方範例

設定依附元件

DataStore 在 1.1.0 以上版本中支援 KMP。

如要在 KMP 專案中設定 DataStore,請在模組的 build.gradle.kts 檔案中新增構件的依附元件:

  • androidx.datastore:datastore - DataStore 程式庫
  • androidx.datastore:datastore-preferences - Preferences DataStore 程式庫

定義 DataStore 類別

您可以在共用 KMP 模組的通用來源中,使用 DataStoreFactory 定義 DataStore 類別。將這些類別放在通用來源中,即可在所有目標平台中共用這些類別。您可以使用 actualexpect 宣告,建立特定平台的實作項目。

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