首页 > 解决方案 > 除非搜索词更改,否则 Transformation.switchmap 不会返回结果

问题描述

我有一个 LiveData<List> 需要根据搜索查询返回帐户,如果没有查询返回所有帐户。这是我的代码,我在我的 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()
                }
            }

        }

有人可以指导我在这里做错了什么。

谢谢

标签: androidkotlinviewmodelandroid-livedata

解决方案


您应该使用初始值。您的 switchMap 在您的 seahTerm 获得第一个值之前不会被触发。

val searchTerm = MutableLiveData<String>("")

推荐阅读