【发布时间】:2020-09-14 05:24:25
【问题描述】:
用例:一个简单的计费应用。
当数量或价格变化时,总量应该变化。
我正在使用 DataBinding,如何通知 UI total 已更改?
型号:
class Detail(){
private var _quantity = BigDecimal.ZERO
private var _price = BigDecimal.ZERO
private var _total = BigDecimal.ZERO
var quantity : BigDecimal
get() = _quantity
set(value){
_quantity = value
compute()
}
//same boilerplate for price
private fun compute(){
total = price.mutiply(quantity)
}
}
视图模型
var instance = Detail()
fun addQuantity(){
instance.quantity.add(1)
}
fun addPrice(){
instance.price.add(1)
}
查看
<button onClick="@{() -> viewModel.addQuantity()}"
<button onClick="@{() -> viewModel.addPrice()}"
<textview text="@{viewModel.instance.total}"/>
我的第一个想法是制作一个 LiveData,但我找不到任何说明在模型中创建 LiveData 属性是个好主意的文档。据我所知,它们应该只在 ViewModel 中。
我还是试过了,但发现另一个问题。我只能让它响应 1 个属性,但它需要响应 2 个属性(数量和价格)
var quantity = MutableLiveData<BigDecimal>()
var price = MutableLiveData<BigDecimal>()
var total = Transformations.map(quantity){ ... }
var total = Transformation.map(price){ ...} // Duplicate property!
什么是正确的方法?
在 .net 世界中,您只需调用 NotifyPropetyChanged(),UI 就会知道。我在 Android 中找不到类似的逻辑。
【问题讨论】:
标签: android kotlin android-livedata android-architecture-components mutablelivedata