在上一届 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 )
与 LiveData
和 map
,以上不能直接实现!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/