android - Kotlin Flow 与 LiveData

标签 android kotlin android-livedata kotlin-coroutines kotlinx.coroutines.flow

在上一届 Google I/O 大会上,Jose Alcerreca 和 Yigit Boyar told us我们不应该再使用 LiveData 来获取数据。现在我们应该使用暂停函数进行一次性获取,并使用 Kotlin 的 Flow 创建数据流。我同意协程非常适合一次性获取或其他 CRUD 操作,例如插入等。但是在我需要数据流的情况下,我不明白 Flow 给了我什么优势。在我看来,LiveData 也在做同样的事情。

流示例:

View 模型

val items = repository.fetchItems().asLiveData()

存储库
fun fetchItems() = itemDao.getItems()


@Query("SELECT * FROM item")
fun getItems(): Flow<List<Item>>

LiveData 示例:

View 模型
val items = repository.fetchItems()

存储库
fun fetchItems() = itemDao.getItems()


@Query("SELECT * FROM item")
fun getItems(): LiveData<List<Item>>

我还希望看到一些使用协程和 Flow 来配合 Room 或 Retrofit 的项目示例。我只找到了一个 Google 的 ToDo sample其中协程用于一次性获取,然后在更改时手动重新获取数据。

最佳答案

Flow有点像 reactive stream (如 rxjava )。有很多不同的运算符,例如 .map , buffer() (无论如何,与 rxJava 相比,运算符的数量更少)。因此,LiveData 之间的主要区别之一和 Flow是你可以订阅 map computation / transformation在其他一些线程中使用

 flowOn(Dispatcher....). 
因此,例如:-
 flowOf("A","B","C").map { compute(it) }.flowOn(Dispatchers.IO).collect {...} // U can change the execution thread of the computation ( by default its in the same dispatcher as collect )
LiveDatamap ,以上不能直接实现!

So its recommended to keep flow in the repository level , and make the livedata a bridge between the UI and the repository !


主要区别在于
  • 一般是普通的flow不是 生命周期感知但 liveData具有生命周期意识。 (我们可以将 stateFlow 与 repeatOnLifecycle 结合使用,使其具有生命周期感知能力)
  • flow有一堆不同的运算符 livedata没有!

  • 但同样,这取决于你如何构建你的项目!

    关于android - Kotlin Flow 与 LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890105/

    相关文章:

    java - 如何将带有 null 条件检查的 java 代码转换为 Kotlin

    android - java.lang.NoSuchMethodError in external java dependency inside the java dependency from Kotlin on Android 5

    android - 带有MVVM的Android自定义对话框

    java - 将 EditText 值保存到 Android 上的 Firebase

    gradle - 什么是 .kotlin_builtins 文件,我可以从我的 uberjars 中省略它们吗?

    java - 调用 arraylist 的 remove(int) 方法从所有类似的 arraylists 中删除该项目

    android - 共享 ViewModel 中的 hasActiveObservers 和 hasObservers false

    java - Android:微调器显示标题栏 1/2 秒

    android - 为什么我在 Google Play 商店找不到官方的 Github 移动应用?