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

标签 android sharedpreferences datastore android-jetpack-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. 转换 block 成功完成,数据存储成功将更改提交到磁盘(没有抛出异常)
  2. 执行转换 block 中的代码时发生异常
  3. 由于从磁盘读取偏好数据或向磁盘写入偏好数据的错误而抛出 IOException

此外,根据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 block 中就可以了。

类似于:

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
    }
}

关于android - 如何监听写入Preferences DataStore的成功或失败结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67844823/

相关文章:

java - 尝试使用 OpenGL 时,由于 NumberFormatException, Activity 崩溃

java - Android 中使用 SharedPreferences 的动态列表

Android Web 浏览器主页

android - 在android中删除sharedPreferences

java - 是否有自动处理流水线的 redis 库?

node.js - 数据存储区使用 Node 获取最后插入的 id

Dropbox API 和数据存储 - 在整个组织中可用吗?

android - 需要 Gradle 版本 2.2。当前版本是 4.4 错误

android - 更改水平进度条颜色

android - Flutter - 如何更改文本字段弹出菜单的样式?