首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当另一个MutableLiveData值更改时通知MutableLiveData

当另一个MutableLiveData值更改时通知MutableLiveData
EN

Stack Overflow用户
提问于 2022-11-06 21:48:35
回答 1查看 39关注 0票数 0

在我的ViewModel中,代码如下所示:

代码语言:javascript
复制
private val _sender = MutableLiveData<DialogListItem.ParticipantItem>()
val sender: LiveData<DialogListItem.ParticipantItem>
    get() = _sender

private val _receiverListItems: MutableLiveData<List<DialogListItem>> =
    CombinedLiveData<List<ParticipantTypeA>, List<ParticipantTypeB>, List<DialogListItem>>(
        _participantsA, _participantsB
    ) { participantsA, participantsB ->
        val sender = _sender.value

        ...
        ...
        
        return@CombinedLiveData ...
    }
val receiverListItems: LiveData<List<DialogListItem>>
    get() = _receiverListItems

当通过执行_sender.postValue(selectedSender)发布一个新值时,应该将该更改通知_receiverListItems。但是,当我记录_sender的值时,我得到了null。如何获得依赖于_receiverListItems值的_sender值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-06 21:56:08

由于您使用的是LiveData的自定义实现,因此这个答案可能限制在它说的内容上,但一般来说,您需要Transformation.switchMap

代码语言:javascript
复制
private val _receiverListItems: LiveData<List<DialogListItem>> =
    Transformation.switchMap(sender).map { sender -> 
        CombinedLiveData<
            List<ParticipantTypeA>, List<ParticipantTypeB>, List<DialogListItem>
        >(
            _participantsA, 
            _participantsB
        ) { participantsA, participantsB ->
           ...
           ...        
        return@CombinedLiveData ...
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74340042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档