我是否遗漏了什么,或者无法在新的Android Jetpack首选项数据存储中附加侦听器?我认为使用Flow的整个重点是我们可以在Preference Datastore上调用flow.toLiveData()并观察值更改的变化。
以下是我如何从Datastore获取Flow。
val taxRatePreferenceFlow: Flow<TaxRate> = dataStore.data
.catch { exception ->
if (exception is IOException){
emit(emptyPreferences())
} else {
throw exception
}
}.map { preferences ->
val name = preferences[PreferencesKeys.TAX_LABEL] ?: "Tax"
val rate = preferences[PreferencesKeys.TAX_RATE] ?: Constants.DEFAULT_TAX_RATE.toFloat()
val type = TaxType.valueOf(preferences[PreferencesKeys.TAX_TYPE] ?: TaxType.ON_ITEMS.name)
TaxRate(name, rate, type)
}
我希望在ViewModel中将Flow转换为LiveData,并监听直到观察者被移除。
totalAmountLiveData.addSource(taxRateFlow.asLiveData()){ taxtRate ->
taxtRate?.let {
updateTaxAmount(it)
}
}
然而,这个观察者只会发出保存的值,并不会在值更新时进行更新。退出并重新进入屏幕时,才能看到更新后的值。
以下是我如何更新DataStore中的每个值:
suspend fun updateTaxLabel(newTaxLabel: String){
dataStore.edit { preferences ->
preferences[PreferencesKeys.TAX_LABEL] = newTaxLabel
}
}
我是否应该使用collect而不是map?如果是,请问有人能在这种情况下给我展示如何使用Flow collect的例子吗?
totalAmountLiveData
是什么?updateTaxAmount()
函数是用来做什么的? - ianhanniballakeupdateTaxAmount(..)
的返回类型是什么? - Achraf Amil