在我的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。如何获得依赖于_receiverListItems值的_sender值?
发布于 2022-11-06 21:56:08
由于您使用的是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 ...
}
}https://stackoverflow.com/questions/74340042
复制相似问题