通常在 ViewModel 中使用 MutableLiveData,然后 ViewModel 只向观察者公开不可变的 LiveData 对象。 https://developer.android.com/topic/libraries/architecture/livedata#update_livedata_objects
将 LiveData 对象作为 ViewModel 对象的参数公开是否更好:
val data: LiveData<String>
get() = _data
或者更确切地说,通过调用成员函数返回它:
fun getData(): LiveData<String> {
return _data
}
所以在第一种情况下我可以写
println(viewModel.data)
而在后者
println(viewModel.getData())