Why there's a separate MutableLiveData subclass of LiveData?

后端 未结 3 667
粉色の甜心
粉色の甜心 2020-11-29 22:34

It looks like MutableLiveData differs from LiveData only by making the setValue() and postValue() methods public, whereas

3条回答
  •  无人及你
    2020-11-29 23:22

    MutableLiveData is extending from LiveData. LiveData's protected methods can only be addressed by self or subclasses. So in this case MutableLiveData being a sub class of LiveData can access these protected methods.

    What you would like to do, is observe on an instance and see if there are any changes. But at the same time you do not want any "outsiders" to change that instance you are observing. In a sense this creates a problem, as you would like to have an object that is and changeable, to update any new status, and not changeable, to make sure nobody who shouldn't can update this instance. These two features conflict with each other but can be solved by creating an extra layer.

    So what you do is extend your class, LiveData, with a class that can access its methods. The sub layer, in this case MutableLiveData, is able to access the protected methods of its parent (/super).

    Now you start creating instances, and create your observer instance of MutableLiveData. At the same time you create a LiveData instance referring to this same instance. Because MutableLiveData extends LiveData, any MutableLiveData instance is a LiveData object and can therefore be referenced by a LiveData variable.

    Now the trick is almost done. You expose only the LiveData instance, nobody can use its protected methods, nor can cast it to it's super (maybe at compile time, but it wouldnt run: RunTime error). And you keep the actual sub class instance private, so it can only be changed by those who own the instance, using the instance's methods.

    //create instance of the sub class and keep this private
    private val _name: MutableLiveData = MutableLiveData()
    //create an instance of the super class referring to the same instance
    val name: LiveData = _name
    
    //assign observer to the super class, being unable to change it
    name.value.observe(.....)
    

    Now the super class notifies when any changes are applied.

    //change the instance by using the sub class
    _name.postValue(...)
    //or _name.setValue(...)
    

    Blockquote Generally speaking, is such a form of inheritance (increasing the visibility of certain methods being the only change) a well-known practice and what are some scenarios where it may be useful (assuming we have access to all the code)?

    Yes, it is quite well-known and this described above is a common scenario. Remove the observer pattern, and just make it in a set/get form would just as much benefit from it. Depending ofc where you implement it, no golden rules in the end.

提交回复
热议问题