Why there's a separate MutableLiveData subclass of LiveData?

Solution 1:

In LiveData - Android Developer Documentation, you can see that for LiveData, setValue() & postValue() methods are not public.

Whereas, in MutableLiveData - Android Developer Documentation, you can see that, MutableLiveData extends LiveData internally and also the two magic methods of LiveData is publicly available in this and they are setValue() & postValue().

setValue(): set the value and dispatch the value to all the active observers, must be called from main thread.

postValue() : post a task to main thread to override value set by setValue(), must be called from background thread.

So, LiveData is immutable. MutableLiveData is LiveData which is mutable & thread-safe.

Solution 2:

This is the whole MutableLiveData.java file:

package androidx.lifecycle;
/**
 * {@link LiveData} which publicly exposes {@link #setValue(T)} and {@link #postValue(T)} method.
 *
 * @param <T> The type of data hold by this instance
*/
@SuppressWarnings("WeakerAccess")
public class MutableLiveData<T> extends LiveData<T> {
    @Override
    public void postValue(T value) {
        super.postValue(value);
    }
    @Override
    public void setValue(T value) {
        super.setValue(value);
    }
}

So yes, the difference comes only by making postValue and setValue public.

One use case that I can recall off of my head is for encapsulation using Backing Property in Kotlin. You can expose LiveData to your Fragment/Activity (UI Controller) even though you can have MutableLiveData for manipulation in your ViewModel class.

    class TempViewModel : ViewModel() {
        ...
        private val _count = MutableLiveData<Int>()
        val count: LiveData<Int>
            get() = _count
        public fun incrementCount() = _count.value?.plus(1)
        ...
    }

This way your UI Controller will only be able to observe values without being able to edit them. Obviously, your UI Controller can edit values using public methods of TempViewModel like incrementCount().

Note: To clarify mutable/immutable confusion -

data class User(var name: String, var age: Int)

class DemoLiveData: LiveData<User>()

var demoLiveData: LiveData<User>? = DemoLiveData()

fun main() {
    demoLiveData?.value = User("Name", 23) // ERROR
    demoLiveData?.value?.name = "Name" // NO ERROR
    demoLiveData?.value?.age = 23  // NO ERROR
}

Solution 3:

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<String> = MutableLiveData<String>()
//create an instance of the super class referring to the same instance
val name: LiveData<String> = _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.