Item.kt类是
@Entity(tableName = "item")
class Item(
val id: Long,
val title: String,
) {
@Ignore
var selection: Boolean = false
}
然后我进行查询以获取表中的所有项目,它返回
LiveData<List<Item>>
然后在viewModel中我想将选择(true)accordig应用于Mutablelivedata selectionId,选择id包含MutableLiveData<Long>
(它包含一个id LiveData<List<Item>>
)
MyViewModel.kt代码如下所示
class MyViewModel(val repository: Repository) : ViewModel() {
..........
......
val selectionId: MutableLiveData<Long> by lazy {
MutableLiveData<Long>()
}
fun setSelectionId(id: Long) {
selectionId.postValue(id)
}
..........
......
val itemLiveList: LiveData<List<Item>> = liveData(Dispatchers.IO) {
emitSource(repository.getItems())
}
}
如果是List<Item>
我可以做这样的事情
val ItemWithSelection: List<Item> = repository.getItems().apply {
this.forEach {
if (it.id == selectionId) {
it.selection = true
}
}
}
但我不知道如何使用 Mediator LiveData 来实现这一点。请帮我