1

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 来实现这一点。请帮我

4

1 回答 1

1

我不了解您代码中的所有内容,例如,我从未见过名为liveData(CoroutineDispatcher). 但你的意思是你想要这样的东西吗?

val listWithoutSelection = liveData(Dispatchers.IO) {
    emitSource(repository.getItems())
}

val listWithSelection = MediatorLiveData<List<Item>>().apply {
    addSource(listWithoutSelection) { updateListSelection() }
    addSource(selectionId) { updateListSelection() }
}

fun updateListSelection() {
    listWithSelection.value = listWithoutSelection.value?.map {
        if (it.id == selectionId.value)
            it.copyWithSelection(true)
        else
            it
    }
}

使用 Kotlin 数据类可以轻松完成 copyWithSelection。不需要取决于您是否要修改从数据库中获取的对象。如果您只在此处使用该对象,则可以始终将其他对象的选择重置为 false,然后您可以保留该对象并且不需要副本。

于 2019-07-02T12:26:24.267 回答