首页 > 解决方案 > 这是 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
}

标签: androidkotlinandroid-roomandroid-livedataandroid-viewmodel

解决方案


这很好,但您可以进行一些更改:

  1. 更改LiveData<MutableList<CategoryItem>>LiveData<List<CategoryItem>>。不要使用 a MutableList,除非你真的必须这样做。在您的情况下,List可以正常工作。

  2. 在您的CategoryRepository而不是获取 in 中init,在getAllCategories()通话期间执行此操作。所以改变你的代码是这样的:fun getAllCategories() = categoryItemDao.getAllCategoryItems()

  3. 同样地做同样的事情CategoryViewModel。将您的代码更改为:fun getAllCategories() = repository.getAllCategories()

一个常见的误解是LiveData仅在数据更改时使用。但事实并非如此。您的 13 个类别可能不会改变,但那是在数据库中。因此,如果您要在没有 a 的情况下完成此LiveData操作,则必须查询数据库并在主线程中填充视图,或者您需要将其包装在后台线程中。但是,如果您通过 执行此操作LiveData,您将免费获得异步响应式编码方式。只要有可能,尽量让你的视图观察到LiveData.


推荐阅读