Usually MutableLiveData is used in the ViewModel and then the ViewModel only exposes immutable LiveData objects to the observers. 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())
最佳答案
在内部,两者基本相同。但正如@tyczj 所说,第一种形式更为惯用。所以,我更喜欢第一个。
关于android - 将 LiveData 对象公开为 ViewModel 的参数还是由成员函数调用返回更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54952424/