我正在学习LiveData,代码A 来自https://github.com/googlecodelabs/android-databinding
我认为代码A 太复杂,因此我尝试将其简化为代码B 。
但是代码B 无法编译,您可以看到图像C ,我该如何解决?
代码A
class SimpleViewModelSolution : ViewModel() {
private val _name = MutableLiveData("Ada")
private val _lastName = MutableLiveData("Lovelace")
private val _likes = MutableLiveData(0)
val name: LiveData<String> = _name
val lastName: LiveData<String> = _lastName
val likes: LiveData<Int> = _likes
// popularity is exposed as LiveData using a Transformation instead of a @Bindable property.
val popularity: LiveData<Popularity> = Transformations.map(_likes) {
when {
it > 9 -> Popularity.STAR
it > 4 -> Popularity.POPULAR
else -> Popularity.NORMAL
}
}
fun onLike() {
_likes.value = (_likes.value ?: 0) + 1
}
}
代码B
class SimpleViewModelSolution : ViewModel() {
val name: LiveData<String> =MutableLiveData("Ada")
val lastName: LiveData<String> = MutableLiveData("Lovelace")
val likes: LiveData<Int> = MutableLiveData(0)
// popularity is exposed as LiveData using a Transformation instead of a @Bindable property.
val popularity: LiveData<Popularity> = Transformations.map(likes) { //The par 'likes' is OK
when {
it > 9 -> Popularity.STAR
it > 4 -> Popularity.POPULAR
else -> Popularity.NORMAL
}
}
fun onLike() {
var a=likes.value //It's OK
likes.value = (likes.value ?: 0) + 1 //Error
}
}
图片C
答案 0 :(得分:1)
将likes
对象初始化为MutableLiveData <>而不是LiveData <>
将您的代码更改为:
val name: LiveData<String> =MutableLiveData("Ada")
val lastName: LiveData<String> = MutableLiveData("Lovelace")
val likes: MutableLiveData<Int> = MutableLiveData<Int>(0)
// popularity is exposed as LiveData using a Transformation instead of a @Bindable property.
val popularity: LiveData<Popularity> = Transformations.map(likes) { //The par 'likes' is OK
when {
it > 9 -> Popularity.STAR
it > 4 -> Popularity.POPULAR
else -> Popularity.NORMAL
}
}
fun onLike() {
var a = likes.value //It's OK
likes.value = (likes.value ?: 0) + 1 //Now it'll work fine
}
答案 1 :(得分:1)
您不能直接更改 LiveData ,但必须使用 MutableLiveData ,我们可以说 LiveData 为 ImmutableLiveData 。 MutableLiveData 进一步为您提供了另外两种方法 postValue 和 setValue ,在文档中对此进行了说明:
https://developer.android.com/reference/android/arch/lifecycle/MutableLiveData
您要做的一切
private val _likes: MutableLiveData<Int> = MutableLiveData()
val likes : LiveData<Int>
get() = _likes
我们上面说过,现在我可以更改LiveData,但是您想提供什么价值,因为您要做的是
fun changeValue(newValue: Int) {
_likes.value = newValue
}
您的活动内
vm.likes.observe(this, Observer{
//ui
}
然后根据需要设置值
vm.changeValue(1)