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

bnlyeluc  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(224)

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

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。如何根据_sender值得到_receiverListItems值?

xhv8bpkk

xhv8bpkk1#

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

private val _receiverListItems: LiveData<List<DialogListItem>> =
    Transformation.switchMap(sender).map { sender -> 
        CombinedLiveData<
            List<ParticipantTypeA>, List<ParticipantTypeB>, List<DialogListItem>
        >(
            _participantsA, 
            _participantsB
        ) { participantsA, participantsB ->
           ...
           ...        
        return@CombinedLiveData ...
    }
}

相关问题