android - 有没有办法将 var toyList 设计为 LiveData> 在 ViewModel 中?
问题描述
以下代码来自项目。
作者在 MainViewModel 中var toyList
设计。LiveData<List<ToyEntry>>?
我认为如果我设计var toyList
成这样会更好,我LiveData<List<ToyEntry>>
该怎么做?
class MainViewModel(application: Application) : AndroidViewModel(application) {
var toyList: LiveData<List<ToyEntry>>? = null
get() {
return field ?: mRepo.toyList.also { field = it }
}
...
}
class ToyRepository private constructor(private val mDatabase: ToyDatabase, private val mExecutors: AppExecutors) {
val toyList: LiveData<List<ToyEntry>>
get() = mDatabase.toyDao().allToys
...
}
interface ToyDao {
@get:Query("SELECT * FROM toys")
val allToys: LiveData<List<ToyEntry>>
...
}
解决方案
如果您想通过不可为空的 LiveData 更改可空的 LiveData,使用相同的方法,观察另一个 LiveData,那么您可以使用转换:
val toyList: LiveData<List<ToyEntry>> = Transformations.map(mRepo.toyList) {
it
}
推荐阅读
- vue.js - Vue Apex Charts 中的倒置填充面积图
- arrays - 使用整数数组自动筛选多个条件
- python - 如何限制python脚本中的长度字符串?
- svn - 为什么 Subversion 认为这是一个冲突?
- java - 在spring-boot-starter-data-elasticsearch中向elasticsearch提交文档时出现索引错误
- python - 在 python 循环中修改字典
- java - JRadioButton 选择后需要单击才能使 ActionListener 生效
- ios - swiftui视图的多态性
- c# - 如何在 docker 容器中运行 C# 单元测试
- search - ArangoSearch:如何在不指定文档字段的情况下进行搜索?