【问题标题】:Proper instance creation of Android's Jetpack DataStore (alpha07 version)Android的Jetpack DataStore(alpha07版本)的正确实例创建
【发布时间】:2021-06-02 14:06:07
【问题描述】:

所以在新的 alpha07 版本中,Android 放弃了 private val dataStore = context.createDataStore(name = "settings_pref"),但是他们使用数据存储的新方式对我不起作用。

自从从“androidx.datastore:datastore-core:1.0.0-alpha06”升级到 alpha07 后,我似乎无法在没有红色代码的情况下使我的数据存储语法正常工作(当我添加上下文时出现错误。数据存储。编辑)。同样降级回 alpha06,以前工作的代码现在不再工作(使用 createDataStore)。

我使用的是他们在main page 上的示例,但除了这个之外,他们仍然没有更新他们的示例。

@Singleton
 class PreferencesManager @Inject constructor(@ApplicationContext context: Context) {
    val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
    
      
        val EXAMPLE_COUNTER = intPreferencesKey("example_counter")
        val exampleCounterFlow: Flow<Int> = context.dataStore.data
            .map { preferences ->
                // No type safety.
                preferences[EXAMPLE_COUNTER] ?: 0
            }
    
        suspend fun incrementCounter() {
            context.dataStore.edit { settings ->
                val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
                settings[EXAMPLE_COUNTER] = currentCounterValue + 1
            }
        }
    }

如果有人知道问题(或我的错误),我将不胜感激。

【问题讨论】:

  • 那么什么不起作用?
  • +1 现在也登陆了,如果有人知道这个问题,为了清楚起见附上图片@ianhanniballake prnt.sc/10cqim3
  • @ianhanniballake 基本上是 Abhishek-an 所展示的内容,上下文、数据存储或编辑都显示为未解决的参考。

标签: android android-studio datastore android-jetpack-datastore


【解决方案1】:

这也让我很吃惊,但我想通了(也就是在成功之前一直猜到):

// Note: This is at the top level of the file, outside of any classes.
private val Context.dataStore by preferencesDataStore("user_preferences")

class UserPreferencesManager(context: Context) {
    private val dataStore = context.dataStore
    // ...
}

这是针对DataStore&lt;Preferences&gt;,但如果您需要自定义序列化程序,可以执行以下操作(与旧方法相同的参数):

// Still top level!
private val Context.dataStore by dataStore(
    fileName = "user_preferences",
    serializer = MyCustomSerializer,
)

【讨论】:

【解决方案2】:

我遇到了同样的问题,发现了一个错误:上下文应该是类的成员才能在任何方法中使用它:

private val Context.dataStore by preferencesDataStore("preferences")
class Preferenses(val context: Context) { get, set, etc}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多