2

首选项 DataStore 提供了一个 edit() 函数,该函数以事务方式更新 DataStore 中的数据。例如,此函数的 transform 参数接受一段代码,您可以在其中根据需要更新值。

suspend fun incrementCounter() {
  context.dataStore.edit { settings ->
    val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
    settings[EXAMPLE_COUNTER] = currentCounterValue + 1
    // can we track success here? i am afraid code might execute asynchronously

  }

我想跟踪它何时成功写入数据存储。我应该把跟踪代码放在哪里?

4

1 回答 1

2

调用edit()是同步的,因此不需要监听器。

根据Preferences DataStore 编辑文档,调用有三种可能的结果edit()

  1. 转换块成功完成,数据存储成功将更改提交到磁盘(不抛出异常)
  2. 在转换块中执行代码期间发生异常
  3. 由于从/向磁盘读取或写入首选项数据的错误而引发 IOException

此外,根据偏好数据存储的 Android 开发人员代码实验室

转换块中 MutablePreferences 的所有更改都将在转换完成后和编辑完成之前应用到磁盘。

所以,我认为将调用包装edit()在 try/catch 块中就可以了。

就像是:

suspend fun incrementCounter() {
    try {
        context.dataStore.edit { settings ->
            val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
            settings[EXAMPLE_COUNTER] = currentCounterValue + 1
        }
        // If you got here, the preferences were successfully committed
    } catch (e: IOException) {
        // Handle error writing preferences to disk
    } catch (e: Exception) {
        // Handle error thrown while executing transform block
    }
}
于 2021-06-04T23:18:55.153 回答