android - 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
}
}
}
如果有人知道问题(或我的错误),我将不胜感激。
解决方案
这也把我扔了,但我想通了(又名,猜测直到它起作用):
// 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,
)
推荐阅读
- javascript - JS filter() 函数 - 有没有办法阻止过滤器达到 0 个结果?
- python - 为什么在 Spyder 上使用 Altair 时我的两个图表都没有显示?
- java - Spring Security 2 种登录方式
- ios - AVAssetWritter 第一帧为空白或黑色
- python - 指定回合数并保存/呈现统计数据,井字游戏
- php - Angular POST 未创建项目
- python - 我的功能不起作用,我不知道为什么。Python
- dataframe - 如何计算数据框中组之间给定二进制变量的百分比
- r - R:使用 lme4、mice 和miceadds 包进行多重插补
- reactjs - 错误边界组件捕获错误但立即消失