Android Jetpack DataStore 的正确实例创建(alpha07 版本)

Bor*_*gar 9 android datastore android-studio android-jetpack-datastore

因此,在新的 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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*ean 12

这也让我感到困惑,但我想通了(也就是猜测直到它起作用):

// 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
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

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