How I can initialize MutableLiveData with initial value? I'm looking for something like:
val text = MutableLiveData<String>("initial value")
“how to initialize livedata kotlin” Code Answerval liveData = MutableLiveData<String>(). default("Initial value!")
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.
The MutableLiveData class exposes the setValue(T) and postValue(T) methods publicly and you must use these if you need to edit the value stored in a LiveData object. Usually MutableLiveData is used in the ViewModel and then the ViewModel only exposes immutable LiveData objects to the observers.
Live data or Mutable Live Data is an observable data holder class. We need this class because it makes it easier to handle the data inside View Model because it's aware of Android Lifecycles such as app components, activities, fragments, and services. The data will always update and aware of its Lifecycles.
MutableLiveData
has been updated and now it has a constructor that accepts an initial value :)
From what I can see, the constructor is available starting from this version:
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha01'
It's a shame they haven't updated MediatorLiveData
to reflect that, though.
2.1.0
is finally stable, so now you can actually see the new constructor in the documentation.
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