【发布时间】:2019-07-02 11:44:11
【问题描述】:
Item.kt 类是
@Entity(tableName = "item")
class Item(
val id: Long,
val title: String,
) {
@Ignore
var selection: Boolean = false
}
然后我进行查询以获取表中的所有项目,它返回
LiveData<List<Item>>
然后在 viewModel 中我想将 selection(true)accordig 应用到 Mutablelivedata selectionId,选择 id 包含 MutableLiveData<Long>(它在 @ 中包含一个 id 987654324@)
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 来实现这一点。请帮帮我
【问题讨论】:
标签: android-architecture-components android-livedata android-viewmodel kotlin-coroutines mutablelivedata