[英]How change MutableLiveData value inside ViewModel
I need to change the value of MutableLiveData in my ViewModel, but I can't make it because the value is equal to null, I think need to establish an observer change it inside that, but I don't know how to do it and whether it's a good idea.我需要在我的 ViewModel 中更改 MutableLiveData 的值,但我无法做到,因为该值等于 null,我认为需要在其中建立一个观察者进行更改,但我不知道该怎么做这是否是个好主意。
AudioRecordersListViewModel AudioRecordersListViewModel
class AudioRecordersListViewModel() : ViewModel() {
var audioRecordsLiveData: MutableLiveData<MutableList<AudioRecordUI>> = MutableLiveData();
private var audioRecordDao: AudioRecordDao? = null
@Inject
constructor(audioRecordDao: AudioRecordDao) : this() {
this.audioRecordDao = audioRecordDao
viewModelScope.launch {
val liveDataItems = audioRecordDao
.getAll().value!!.map { item -> AudioRecordUI(item) }
.toMutableList()
if (liveDataItems.size > 0) {
liveDataItems[0].isActive = true
}
audioRecordsLiveData.postValue(liveDataItems)
}
}
}
AudioRecordDao AudioRecordDao
@Dao
interface AudioRecordDao {
@Query("SELECT * FROM AudioRecordEmpty")
fun getAll(): LiveData<MutableList<AudioRecordEmpty>>
}
First of all, using !!
首先,使用
!!
is not a good idea it can easily lead to NullPointer Exception, us ?
不是一个好主意它很容易导致NullPointer Exception,我们
?
instead.反而。
You can set an empty list on your LiveData and add new data to that List:您可以在 LiveData 上设置一个空列表并将新数据添加到该列表中:
var audioRecordsLiveData: MutableLiveData<MutableList<AudioRecordUI>> = MutableLiveData();
init {
audioRecordsLiveData.value = mutableListOf()
}
If you need to observe that LiveData:如果您需要观察 LiveData:
mViewModel.mLiveData.observe(this, Observer { list ->
if (list.isNotEmpty()) {
//Update UI Stuff
}
})
never set your LiveData inside Fragment/Activity永远不要在 Fragment/Activity 中设置你的 LiveData
If you need to update your LiveData:如果您需要更新 LiveData:
mViewModel.onSomethingHappened()
Inside ViewModel:内部视图模型:
fun onSomethingHappened() {
...
...
...
mLiveData.value = NEW_VALUE
}
If you want to update your LiveData from another thread use:如果您想从另一个线程更新您的 LiveData,请使用:
mLiveData.postValue()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.