livedata和mutableLiveData有什么区别?什么时候都能观察到新的值?
发布于 2022-04-17 19:53:26
MutableLiveData和LiveData之间唯一的关键区别是您可以更改MutableLiveData的值,但是LiveData不允许您更改它的值。LiveData只允许您观察和使用它的值。
它们通常一起使用,MutableLiveData用于记录更改的值,LiveData用于通知UI更改的值。,例如
class SampleViewModel(): ViewModel() {
private val _sampleString = MutableLiveData<String>()
val sampleString: LiveData<String> get() = _sampleString
fun setSampleString(temp: String) {
_sampleString.value = temp
}
}
class MainActivity: AppCompatActivtiy {
private val viewModel: SampleViewModel by viewModels()
//in onCreate
viewModel.sampleString.observe(this) {
//here you will have the value sampleString, that you can use as you want.
}
//that is how you can update the value of MutableLiveData
viewModel.setSampleString("random string")
}
在这里,一旦您将该值赋值给_sampleString,sampleString,sampleString将被通知并通知其中所做的更改。LiveData在MutableLiveData中更新新值后立即观察新值。
我希望这能消除你的疑虑。
https://stackoverflow.com/questions/71904507
复制相似问题