How to access each element of LiveData<List<MVoice>> with Kotlin?

Viewed 426

The Code A use for (aMovice in listVoiceBySort.value!!) to access each element of LiveData<List<MVoice>>.

But I don't think it's a good way because it uses listVoiceBySort.value!!, it's ugly.

Is there a good way to access each element of LiveData<List<MVoice>>?

Code A

 val listVoiceBySort: LiveData<List<MVoice>> =_listVoiceBySort

 fun selectAllIDs(){
   for (aMovice in listVoiceBySort.value!!){
            selectedIDs.add(aMovice.id)
    }
 }
2 Answers

It would be better to use forEach i.e. an inline function with the same functionality. It lets you use safe calls (?.) instead of not null assertion (!!):

fun selectAllIDs() {
    listVoiceBySort.value?.forEach {
        selectedIDs.add(it.id)
    }
}

Another way is to map MVoice elements to their ids and then add them all to the selectedIDs:

fun selectAllIDs() {
    listVoiceBySort.value?.map { it.id }?.let {
        selectedIDs.addAll(it)
    }
}

Generally data inside a livedata is accessed via an observer where you get a non-null value

listVoiceBySort.observe(lifecycleOwner, Observer {
    for(mVoice in it){
    ...
    }
}
Related