when to use MutableLiveData
and LiveData
means the area of using the methods :
MutableLiveData<User> getUser() { if (userMutableLiveData == null) { userMutableLiveData = new MutableLiveData<>(); } return userMutableLiveData; }
and when to use this,
LiveData<User> getUser() { if (userMutableLiveData == null) { userMutableLiveData = new MutableLiveData<>(); } return userMutableLiveData }
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.
MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide. LiveData/MutableLiveData is commonly used in updating data in a RecyclerView from a collection type(List, ArrayList etc).
LiveData notifies Observer objects when underlying data changes. You can consolidate your code to update the UI in these Observer objects. That way, you don't need to update the UI every time the app data changes because the observer does it for you. No memory leaks.
Else, we can use callback or RxJava in ViewModel. Another compromise is implement MediatorLiveData (or Transformations) and observe (put your logic here) in ViewModel. Notice MediatorLiveData observer won't trigger (same as Transformations) unless it's observed in Activity/Fragment.
LiveData has no public method to modify its data.
LiveData<User> getUser() { if (userMutableLiveData == null) { userMutableLiveData = new MutableLiveData<>(); } return userMutableLiveData }
You can't update its value like getUser().setValue(userObject)
or getUser().postValue(userObject)
So when you don't want your data to be modified use LiveData
If you want to modify your data later use MutableLiveData
Let's say you're following MVVM architecture and having LiveData
as observable pattern from ViewModel
to your Activity
. So that you can make your variable as LiveData
object exposing to Activity
like below :
class MyViewModel : ViewModel() { // LiveData object as following var someLiveData: LiveData<Any> = MutableLiveData() fun changeItsValue(someValue: Any) { (someLiveData as? MutableLiveData)?.value = someValue } }
And now at Activity
part, you can observe LiveData
but for modification you can call method from ViewModel
like below :
class SomeActivity : AppCompatActivity() { // Inside onCreateMethod of activity val viewModel = ViewModelProviders.of(this)[MyViewModel::class.java] viewModel.someLiveData.observe(this, Observer{ // Here we observe livedata }) viewModel.changeItsValue(someValue) // We call it to change value to LiveData // End of onCreate }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With