Why there's a separate MutableLiveData subclass of LiveData?

39,459

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.

Share:
39,459

Related videos on Youtube

Alexander Kulyakhtin
Author by

Alexander Kulyakhtin

Updated on July 08, 2022

Comments

  • Alexander Kulyakhtin
    Alexander Kulyakhtin almost 2 years

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

    What are some reasons to make a separate class for this change and not simply define those methods as public in the LiveData itself?

    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)?

    • Blackbelt
      Blackbelt over 6 years
      it is a design decision. LiveData is immutable, since the client can't change the internal state, therefore thread-safe
  • Elliptica
    Elliptica almost 6 years
    It's not really that LiveData is immutable, just that it can't be modified outside of the ViewModel class. The ViewModel class can modify it however it wants (e.g. a timer ViewModel). You would use MutableLiveData if you wanted to modify it outside of the ViewModel class.
  • Pavel Poley
    Pavel Poley over 5 years
    in which scenarios i need to use custom livedata class?
  • Dr4ke the b4dass
    Dr4ke the b4dass over 5 years
    Let's take this scenario, an app with the repository pattern(Server + Room) where Room is the Single Source of truth. App get data only from Room, while Room get it's update from the server. Is mutableLiveData the must use because the data from the server update Room, or LiveData can be use?
  • Serdar Samancıoğlu
    Serdar Samancıoğlu over 5 years
    LiveData is abstract, so you cannot create directly a LiveData object without extending it. MutableLiveData extends LiveData.
  • Kurt Huwig
    Kurt Huwig over 4 years
    postValue may be called from any thread. setValue has to be called by the main thread.
  • Daniel
    Daniel over 4 years
    Links to LiveData and MutableLiveData direct to deprecated documentation. Why when I suggested an edit with actual links it was rejected?
  • Sneh Pandya
    Sneh Pandya over 4 years
    @Daniel not sure why it was rejected by other reviewers in the review queue. I've approved the change, thanks! :)
  • IgorGanapolsky
    IgorGanapolsky over 4 years
    When do we want to use mutable LiveData vs regular LiveData?
  • IgorGanapolsky
    IgorGanapolsky over 4 years
    What is _score?
  • Mooing Duck
    Mooing Duck about 4 years
    @IgorGanapolsk The Repo (and maybe ViewModel) should use a mutable LiveData to represent data that mutates. The Views should always just use LiveData.