繁体   English   中英

如何在LiveData中更改类的特定属性值 <List<T> &gt;(在我的情况下是LiveData <List<Item> &gt;)使用MediatorLiveData

[英]How to change particular property value of a class in a LiveData<List<T>> (in my case LiveData<List<Item>>) using MediatorLiveData

Item.kt类是

@Entity(tableName = "item")
class Item(
    val id: Long,
    val title: String,
    ) {
    @Ignore
    var selection: Boolean = false
}

然后我进行查询以获取表中的所有项目,并返回

LiveData<List<Item>>

然后在viewModel中,我要对Mutablelivedata selectionId应用选择 (true)一致,选择ID包含MutableLiveData<Long> (它在LiveData<List<Item>>包含一个ID)

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实现此目的。 请帮我

我不了解您代码中的所有内容,例如,我从未见过一个名为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,然后可以保留该对象,而无需副本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM