Android Dev Summit, October 23-24: two days of technical content, directly from the Android team. Sign-up for livestream updates.

MutableLiveData

public class MutableLiveData
extends LiveData<T>

java.lang.Object
   ↳ androidx.lifecycle.LiveData<T>
     ↳ androidx.lifecycle.MutableLiveData<T>


LiveData which publicly exposes setValue(T) and postValue(T) method.

Summary

Public constructors

MutableLiveData(T value)

Creates a MutableLiveData initialized with the given value.

MutableLiveData()

Creates a MutableLiveData with no value assigned to it.

Public methods

void postValue(T value)

Posts a task to a main thread to set the given value.

void setValue(T value)

Sets the value.

Inherited methods

Public constructors

MutableLiveData

public MutableLiveData (T value)

Creates a MutableLiveData initialized with the given value.

Parameters
value T: initial value

MutableLiveData

public MutableLiveData ()

Creates a MutableLiveData with no value assigned to it.

Public methods

postValue

public void postValue (T value)

Posts a task to a main thread to set the given value. So if you have a following code executed in the main thread:

 liveData.postValue("a");
 liveData.setValue("b");
 
The value "b" would be set at first and later the main thread would override it with the value "a".

If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.

Parameters
value T: The new value

setValue

public void setValue (T value)

Sets the value. If there are active observers, the value will be dispatched to them.

This method must be called from the main thread. If you need set a value from a background thread, you can use postValue(Object)

Parameters
value T: The new value