There are two ways that make change value of MutableLiveData
. But what is difference between setValue()
& postVa
setValue()
Sets the value. If there are active observers, the value will be dispatched to them.
This method must be called from the main thread.
postValue
If you need set a value from a background thread, you can use
postValue(Object)
Posts a task to a main thread to set the given value.
If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.
This is not a direct answer to the above problem. The answers from Sagar and w201 are awesome. But a simple rule of thumb I use in ViewModels for MutableLiveData is:
private boolean isMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
private MutableLiveData<Boolean> mutVal = new MutableLiveData<>(false);
public LiveData<Boolean> getMutVal() { return this.mutVal; }
public void setMutVal(boolean val) {
if (isMainThread()) mutVal.setValue(val);
else mutVal.postValue(val);
}
Replace mutVal
with your desired value.
Based on the documentation:
setValue():
Sets the value. If there are active observers, the value will be dispatched to them. This method must be called from the main thread.
postValue():
Posts a task to a main thread to set the given value. If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.
To summarize, the key difference would be:
setValue()
method must be called from the main thread. But if you need set a value from a background thread, postValue()
should be used.
All above answers are correct. But one more important difference. If you call postValue()
on field that has no observers and after that you call getValue()
, you don't receive the value that you set in postValue()
. So be careful if you work in background threads without observers.
setValue()
method must be called from the main thread. If you need set a value from a background thread, you can use postValue()
.
More here .
setValue()
is called directly from caller thread, synchronously notifies observers and changes LiveData
value immediately. It can be called only from MainThread.
postValue()
uses inside something like this new Handler(Looper.mainLooper()).post(() -> setValue())
, so it runs setValue
via Handler
in MainThread. It can be called from any thread.