android - 这是 LiveData 的正确使用方式吗?

标签 android kotlin android-room android-livedata android-viewmodel

我目前正在将 Room + ViewModel + LiveData 应用到我的项目中。 在我的应用程序中,“显然”需要观察数据,但不是全部。

下面的代码是 category 数据的示例代码。在我的情况下,类别数据没有改变并且始终保持相同的值状态(13个类别和内容没有改变)。类别是通过 CategoryItemDao 类从数据库加载的数据。

类目数据需要用livedata包裹吗? 或者除了其 observable 功能之外,还有足够的理由使用 LiveData 吗?

我已经多次阅读 LiveData 指南,但我不了解确切的概念。

CategoryItemDao

@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
}

类别 View 模型

class CategoryViewModel(application: Application) : AndroidViewModel(application) {
    private val repository = CategoryRepository(application)
    private val allCategories: LiveData<MutableList<CategoryItem>>

    init {
        allCategories = repository.getAllCategories()
    }

    fun getAllCategories() = allCategories
}

最佳答案

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

  1. 更改 LiveData<MutableList<CategoryItem>>LiveData<List<CategoryItem>> .不要使用 MutableList除非你真的必须。在你的情况下,List会工作得很好。

  2. 在你的CategoryRepository而不是获取 init , 在 getAllCategories() 期间进行称呼。所以像这样更改您的代码:fun getAllCategories() = categoryItemDao.getAllCategoryItems()

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

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

关于android - 这是 LiveData 的正确使用方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51947757/

相关文章:

java - 将光标放在 EditText 中文本的末尾

android - 获取 Room Persistence Library Android 的 onUpgrade() 回调

android - 如何在 Android 中覆盖 LiveData toString

与位置比较时的 Java : Format the distances properly,

android - 警告 : shared library text segment is not shareable

java - 从 Viewholder 通知 RecyclerView Adapter 的最佳方式?

android - 房间数据库迁移 fallbackToDestructiveMigration() 不工作

java - 在android中将Spinner String值 "20-34"转换为从20到34的整数

swift - 有没有办法在 Kotlin 中完成 Swift 的协议(protocol)组合

kotlin - 如何检查字符串是否是android中的有效电子邮件?