Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why private set is not working to MutableLiveData?

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?

like image 717
Sergey Shustikov Avatar asked Dec 03 '18 11:12

Sergey Shustikov


People also ask

What is difference between live data and MutableLiveData?

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.

Is MutableLiveData thread-safe?

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).

What is the use of MutableLiveData?

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.


1 Answers

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.

like image 106
tynn Avatar answered Sep 28 '22 08:09

tynn