因此,在新的 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
}
}
}
如果有人知道问题(或我的错误),我将不胜感激。