Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of setValue() & postValue() in MutableLiveData

People also ask

What is the difference between mutable live data and live data?

By using LiveData we can only observe the data and cannot set the data. MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods (the former being thread-safe) so that we can dispatch values to any live or active observers.

Why there is need of setValue if we can use postValue from Main & background thread?

This is because the postValue() method is to post the changes to the main thread and this change will be applied once the main thread will be executed. So, the value will be overridden by “a”.

Which of the method will update the value inside a MutableLiveData?

While using the Main thread to change the data, you should use the setValue method of the MutableLiveData class and while using the background thread to change the LiveData, you should use the postValue method of the MutableLiveData class.


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 of the above answers are correct. But one more important difference. If you call postValue() and after that you call getValue(), you may not receive the value that you set in postValue(). If the main thread had already set the value, then you will get the value that you posted, but if the main thread hadn't set the value yet, then you don't get the value that you posted. So be careful if you work in background threads.


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.


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.