何时使用MutableLiveData和LiveData意味着使用以下方法的区域:
MutableLiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData;
}什么时候用这个,
LiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData
}发布于 2019-04-30 06:27:59
LiveData没有修改其数据的公共方法。
LiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData
}您不能像getUser().setValue(userObject)或getUser().postValue(userObject)那样更新它的值
因此,当您不希望修改数据时,请使用LiveData,如果以后要修改数据,请使用MutableLiveData
发布于 2019-04-30 06:23:25
假设您遵循MVVM体系结构,并将LiveData作为从ViewModel到Activity的可观察模式。这样,您就可以将变量作为LiveData对象公开给Activity,如下所示:
class MyViewModel : ViewModel() {
// LiveData object as following
var someLiveData: LiveData<Any> = MutableLiveData()
fun changeItsValue(someValue: Any) {
(someLiveData as? MutableLiveData)?.value = someValue
}
}现在,在Activity部件上,您可以观察到LiveData,但是对于修改,您可以从ViewModel调用方法,如下所示:
class SomeActivity : AppCompatActivity() {
// Inside onCreateMethod of activity
val viewModel = ViewModelProviders.of(this)[MyViewModel::class.java]
viewModel.someLiveData.observe(this, Observer{
// Here we observe livedata
})
viewModel.changeItsValue(someValue) // We call it to change value to LiveData
// End of onCreate
}发布于 2021-07-31 09:30:22
LiveData没有更新存储数据的公共可用方法。MutableLiveData类公开了setValue(T)和postValue(T)方法,如果需要编辑存储在LiveData对象中的值,则必须使用这些方法。通常,MutableLiveData在ViewModel中使用,然后ViewModel只向观察者公开不可变的LiveData对象。请看一下这个参考文献。
https://stackoverflow.com/questions/55914752
复制相似问题