I'm wondering if there is a better (e.g. less code...
# android
t
I'm wondering if there is a better (e.g. less code) way to do this, in my ViewModel i want to have a LiveData object that can only be changed from the viewModel it self (e.g. the view should not change it, only observe), I use the next code for this, is there a better way of doing this?
Copy code
private val _someData = MutableLiveData<String>()
    val someData: LiveData<String> = _someData
g
nope, there is no better way
t
😞 , but thanks
j
They got it in a compose with a delegate, can it be ported to livedata?
image.png
t
not sure as the todoItems is a var that changes so you would be observing a different liveData object
g
this approach from screenshot is not related
property itself is still mutable
it would be the same as
Copy code
var someData: MutableLiveData<String> = MutableLiveData<String>()
you can hack it a bit by casting to MutableLiveData() in places where you want to update it, it’s kinda fine if it implementation detail, though it doesn’t allow to have defensive copy (but you don’t have it now too)
o
Copy code
fun <T> LiveData<T>.unsafePost(value: T) = (this as MutableLiveData).postValue(value)

------------

val data: LiveData<Foo> = MutableLiveData(Foo.empty())

data.unsafePost(Foo(Bar()))
If you are the owner of that LiveData, there's no harm in casting.
c
If you have a ViewModel base class or interface, then put the extension function, proposed by @okarm, in that. Then only the view model can use unsafePost().
j
There is a KEEP to have that behavior without needing a base class. Hope 1.5 add it