Ofir Bar
02/28/2020, 1:47 PMLiveData
.
I wonder, why can’t I call postValue
or setValue
If I subclass a LiveData?
private val someInstanceOfLiveData = object : LiveData<String>(){}
fun test(){
someInstanceOfLiveData.setValue() // Cannot access 'setValue': it is protected/*protected and package*/ in '<no name provided>'
someInstanceOfLiveData.postValue() // Cannot access 'postValue': it is protected/*protected and package*/ in '<no name provided>'
}
from my understanding, object : LiveData<String>(){}
is a subclass of the abstract LiveData
class.
If it is a subclass, why can’t I call postValue()/setValue()
, which are declared as protected
inside the LiveData
?Samme Kleijn
02/28/2020, 1:49 PMMutableLiveData
Ofir Bar
02/28/2020, 1:50 PMMutableLiveData
is a subclass of LiveData
.
But why I can’t subclass LiveData and call postValue/setValue on it?Adam Powell
02/28/2020, 1:51 PMLiveData
is read-only, not immutable. It can change, but it doesn't expose permission to change it.Samme Kleijn
02/28/2020, 1:54 PMOfir Bar
02/28/2020, 1:56 PMAdam Powell
02/28/2020, 2:00 PM{}
that comes after your object : LiveData<String>()
. You're trying to call them from outside, which would break encapsulation of protected
.Ofir Bar
02/28/2020, 2:09 PMMutableLiveData
does is just taking the postValue() and setValue(), and overriding it simply for the sake of making the methods public.
I did something similar now:
private val someInstanceOfLiveData = object : LiveData<String>(){
public override fun setValue(value: String?) {
super.setValue(value)
}
public override fun postValue(value: String?) {
super.postValue(value)
}
}
fun test(){
someInstanceOfLiveData.setValue("")
someInstanceOfLiveData.postValue("")
}
Thank you my friend 🙂 🍕🍻
@Adam Powell