【问题标题】:Transformation.switchmap not returning result unless search term changes除非搜索词更改,否则 Transformation.switchmap 不会返回结果
【发布时间】:2021-02-06 08:03:40
【问题描述】:

我有一个 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()
                }
            }

        }

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

谢谢

【问题讨论】:

    标签: android kotlin viewmodel android-livedata


    【解决方案1】:

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

    val searchTerm = MutableLiveData<String>("")
    

    【讨论】:

    • 成功了,谢谢,我以前用过LiveData,从来不需要像这样初始化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2015-05-20
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多