【问题标题】:How to change particular property value of a class in a LiveData<List<T>> (in my case LiveData<List<Item>>) using MediatorLiveData如何使用 MediatorLiveData 更改 LiveData<List<T>>(在我的情况下为 LiveData<List<Item>>)中类的特定属性值
【发布时间】: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&lt;Long&gt;(它在 @ 中包含一个 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&lt;Item&gt;,我可以这样做


 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


    【解决方案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,然后您可以保留该对象并且不需要副本。

    【讨论】:

    • 你把 liveData 当作普通列表,要解决这个问题我们需要 MediatorLiveData 但我不知道在这种情况下如何使用跨度>
    • @d-feverx 我的示例将在首次加载项目列表时正确设置选择。我将其视为列表的 LiveData,这就是为什么那里有一个 value 调用。你的意思是你希望它在选择更新时更新?从代码示例中我不清楚,因为您只将 it.selection 设置为 true,但如果它发生更改则永远不会设置为 false。
    • 是的,我希望 itemLive 列表在选择更新时更新,这就是为什么我将选择 id 设为 mutableLivedata 类型的原因
    • @d-feverx 我明白了。我将解决方案更改为使用 MediatorLiveData。我想我明白你的意思了。你可能想在你的问题中说清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多