如何监听写入Preferences DataStore的成功或失败结果?

How to listen to the success or failure result of writing to Preferences DataStore?

Preferences DataStore 提供了一个 edit() 函数,可以事务性地更新 DataStore 中的数据。例如,此函数的转换参数接受一个代码块,您可以在其中根据需要更新值。

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

  }

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

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

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

  1. 转换块成功完成,数据存储成功将更改提交到磁盘(未抛出异常)
  2. 在转换块中执行代码时出现异常
  3. 由于读取或写入首选项数据时出错,抛出 IOException from/to disk

进一步,根据Android developer codelab for preferences datastore

All changes to MutablePreferences in the transform block will be applied to disk after transform completes and before edit completes.

所以,我认为将对 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
    }
}