vin*_*yak 8 android android-livedata android-architecture-components
何时使用MutableLiveData以及LiveData使用方法的范围:
MutableLiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData;
}
Run Code Online (Sandbox Code Playgroud)
以及何时使用
LiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData
}
Run Code Online (Sandbox Code Playgroud)
Jee*_*ede 13
比方说,你在下面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
}
}
Run Code Online (Sandbox Code Playgroud)
现在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
}
Run Code Online (Sandbox Code Playgroud)
我们应该返回 LiveData 以防止视图(或其他观察者)意外修改值。
拥有:
LiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData
}
Run Code Online (Sandbox Code Playgroud)
你不能在你的活动/片段中写:getUser().setValue(...)。这使您的代码不易出错。
LiveData没有公共方法来修改其数据。
LiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData
}
Run Code Online (Sandbox Code Playgroud)
您无法像getUser().setValue(userObject)或那样更新其值getUser().postValue(userObject)
因此,当您不希望修改数据时,LiveData
如果以后要修改数据,请使用MutableLiveData