I have a code
var exampleData = MutableLiveData<String>()
private set
And I want to hide setter to value of MutableLiveData
exampleData.value = "Hi!" // still working
I tried several ways, but all are working!
var exampleData = MutableLiveData<String>()
private set(value) { field = value } // Working!
var exampleData = MutableLiveData<String>()
internal set // Working!
var exampleData = MutableLiveData<String>()
internal set(value) { field = value } // Working!
How to hide this setter?
LiveData is immutable by default. By using LiveData we can only observe the data and cannot set the data. MutableLiveData is mutable and is a subclass of LiveData.
MutableLiveData is LiveData which is mutable & thread-safe. It's not really that LiveData is immutable, just that it can't be modified outside of the ViewModel class. The ViewModel class can modify it however it wants (e.g. a timer ViewModel).
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.
The setter of the property has no relevance for your MutableLiveData
, as its mutability within the object itself. You'd have to cast it to LiveData
, which you could be done with a backing property.
private val _exampleData = MutableLiveData<String>()
val exampleData: LiveData<String> get() = _exampleData
You can change the value privately with _exampleData.value = "value"
and expose only an immutable LiveData
.
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