我有一个LiveData,它需要返回基于搜索查询的帐户,如果没有查询返回所有帐户。这是我的代码,我在我的ViewModel类中使用过,但在初始化时没有账户显示,只有当我更改searchTerm时,它才开始显示结果,并且在将搜索词设置为空时也显示结果。
val searchTerm = MutableLiveData<String>()
val accounts : LiveData<List<AccountModel>> = Transformations.switchMap(searchTerm){
if(it.isNullOrEmpty()){
Transformations.map(accountRepository.accountDAO.getAccounts()){
it.toDomainModel()
}
}else{
Transformations.map(accountRepository.accountDAO.getSearchedList(it)){
it.toDomainModel()
}
}
}有没有人能告诉我我到底做错了什么。
谢谢
发布于 2021-02-06 16:12:00
您应该使用初始值。在searhTerm获得第一个值之前,不会触发switchMap。
val searchTerm = MutableLiveData<String>("")https://stackoverflow.com/questions/66074764
复制相似问题