https://kotlinlang.org logo
#android
Title
# android
o

Ofir Bar

02/28/2020, 1:47 PM
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

Samme Kleijn

02/28/2020, 1:49 PM
LiveData is immutable, use
MutableLiveData
o

Ofir Bar

02/28/2020, 1:50 PM
@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

Adam Powell

02/28/2020, 1:51 PM
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

Samme Kleijn

02/28/2020, 1:54 PM
Sorry, made a mistake, indeed I meant read-only.
o

Ofir Bar

02/28/2020, 1:56 PM
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

Adam Powell

02/28/2020, 2:00 PM
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

Ofir Bar

02/28/2020, 2:09 PM
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
3 Views