android - 这是 LiveData 使用的正确方法吗?
问题描述
我目前正在将Room
++ViewModel
应用LiveData
到我的项目中。在我的应用程序中,“显然”需要观察数据,但不是全部。
下面的代码是category
数据的示例代码。在我的情况下,类别数据不会改变并且始终保持相同的值状态(13 个类别和内容不会改变)。类别是通过类从数据库加载的数据CategoryItemDao
。
类别数据是否需要用 livedata 包装?或者除了它的observerable
功能之外,还有足够的理由使用 LiveData 吗?
我已经多次阅读 LiveData 指南,但我不明白确切的概念。
分类ItemDao
@Dao
interface CategoryItemDao {
@Query("SELECT * FROM CategoryItem")
fun getAllCategoryItems(): LiveData<MutableList<CategoryItem>>
}
类别存储库
class CategoryRepository(application: Application) {
private val categoryItemDao: CategoryItemDao
private val allCategories: LiveData<MutableList<CategoryItem>>
init {
val db = AppDatabase.getDatabase(application)
categoryItemDao = db.categoryItemDao()
allCategories = categoryItemDao.getAllCategoryItems()
}
fun getAllCategories() = allCategories
}
类别视图模型
class CategoryViewModel(application: Application) : AndroidViewModel(application) {
private val repository = CategoryRepository(application)
private val allCategories: LiveData<MutableList<CategoryItem>>
init {
allCategories = repository.getAllCategories()
}
fun getAllCategories() = allCategories
}
解决方案
这很好,但您可以进行一些更改:
更改
LiveData<MutableList<CategoryItem>>
为LiveData<List<CategoryItem>>
。不要使用 aMutableList
,除非你真的必须这样做。在您的情况下,List
可以正常工作。在您的
CategoryRepository
而不是获取 in 中init
,在getAllCategories()
通话期间执行此操作。所以改变你的代码是这样的:fun getAllCategories() = categoryItemDao.getAllCategoryItems()
同样地做同样的事情
CategoryViewModel
。将您的代码更改为:fun getAllCategories() = repository.getAllCategories()
一个常见的误解是LiveData
仅在数据更改时使用。但事实并非如此。您的 13 个类别可能不会改变,但那是在数据库中。因此,如果您要在没有 a 的情况下完成此LiveData
操作,则必须查询数据库并在主线程中填充视图,或者您需要将其包装在后台线程中。但是,如果您通过 执行此操作LiveData
,您将免费获得异步响应式编码方式。只要有可能,尽量让你的视图观察到LiveData
.
推荐阅读
- excel - 查询的电源查询顺序
- google-chrome - Chrome 扩展:从内容到后台脚本的消息传递
- javascript - 解释 Chrome 开发工具中的丢帧
- c++ - CreateProcess 无法运行 sfc.exe ?为什么
- kubernetes - 我应该在微服务应用程序中的哪里实现忘记密码功能?
- php - 在 laravel 中存储为 .tmp 的图像
- html - 我的代码中的悬停不起作用,我正在使用 sass
- google-chrome - chrome浏览器的网络进程什么时候关闭
- python - 如何通过允许用户使用 plotly 和 python with streamlit 选择列来绘制条形图
- python - 我将如何过滤格式与其他格式不同的 pandas 数据框中的数据?