Search code examples
androidkotlinandroid-architecture-components

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?


Solution

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