Hey guys, for the sake of studying, I am digging i...
# android
o
Hey guys, for the sake of studying, I am digging inside the code of the abstract class
LiveData
. I wonder, why can’t I call
postValue
or
setValue
If I subclass a LiveData?
Copy code
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
?
s
LiveData is immutable, use
MutableLiveData
o
@Samme Kleijn This does not answer my question. I know
MutableLiveData
is a subclass of
LiveData
. But why I can’t subclass LiveData and call postValue/setValue on it?
a
Only the subclass itself can call protected methods. You're trying to call the mutator methods from outside.
@Samme Kleijn
LiveData
is read-only, not immutable. It can change, but it doesn't expose permission to change it.
s
Sorry, made a mistake, indeed I meant read-only.
o
Hey @Adam Powell “Only the subclass itself can call protected methods” Isn’t my anonymous object a subclass of the LiveData too? So do you mean that only the fact that I call it outside of the androidx.lifecycle package is what blocking me?
a
No, what's blocking you is that you're trying to call it from outside of your subclass declaration - you can only call them inside the
{}
that comes after your
object : LiveData<String>()
. You're trying to call them from outside, which would break encapsulation of
protected
.
👍 3
o
Ohhhhh now I get it! so what
MutableLiveData
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:
Copy code
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
👍 3