首页 > 解决方案 > Android的Jetpack DataStore(alpha07版本)的正确实例创建

问题描述

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

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

我正在使用的是他们在主页上的示例,但是除了这个之外,他们还没有更新他们的示例。

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

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

标签: androidandroid-studiodatastoreandroid-jetpack-datastore

解决方案


这也把我扔了,但我想通了(又名,猜测直到它起作用):

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

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

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

推荐阅读