android - 除非搜索词更改,否则 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()
}
}
}
有人可以指导我在这里做错了什么。
谢谢
解决方案
您应该使用初始值。您的 switchMap 在您的 seahTerm 获得第一个值之前不会被触发。
val searchTerm = MutableLiveData<String>("")
推荐阅读
- ruby-on-rails - 多态belongs_to 必须在范围内恰好具有主要类型之一
- json - 当 SQLite 中的键从一行到另一行不同时,如何访问 json 值?
- python-3.x - 在 Python 3 中实现呼吸优先搜索(如何将 'Set' 转换为 'Dictionary'
- javascript - 使用 JavaScript 保持 DIV 的比例
- wso2 - 无法在 wso2 IS 中看到自定义属性查找器为 KM 5.10.0
- android - Firebase 分析数据收集:日志消息
- google-sheets - 参考单元格中有 weeknum() 并导致不同单元格中的公式错误
- react-native - 当expo av本机控件被触发/调用时触发回调?
- vb.net - 如何从列表视图中调用项目
- python - Pygame中的翻转布尔值(主菜单)