Kotlin Flow与LiveData [英] Kotlin Flow vs LiveData

查看:60
本文介绍了Kotlin Flow与LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在上次Google I/O中,何塞·阿尔塞雷卡(Jose Alcerreca)和伊吉特·博亚尔(Yigit Boyar)告诉我们我们不再应该使用LiveData来获取数据.现在,我们应该将暂停功能用于一次抓取,并使用Kotlin的Flow创建数据流.我同意协程对于单次获取或其他CRUD操作(例如插入等)非常有用.但是,在需要数据流的情况下,我不明白Flow给我带来了什么好处.在我看来,LiveData也在这样做.

In the last Google I/O, Jose Alcerreca and Yigit Boyar told us that we should no longer use LiveData to fetch data. Now we should use suspend functions for one-shot fetches and use Kotlin's Flow to create a data stream. I agree that coroutines are great for one-shot fetching or other CRUD operations, such as inserting, etc. But in cases where I need a data stream, I don’t understand what advantages Flow gives me. It seems to me that LiveData is doing the same.

流程示例:

Example with Flow:

ViewModel

ViewModel

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

存储库

fun fetchItems() = itemDao.getItems()

Dao

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

带有LiveData的示例:

Example with LiveData:

ViewModel

ViewModel

val items = repository.fetchItems()

存储库

fun fetchItems() = itemDao.getItems()

Dao

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

我还想看到一些使用协程和Flow与Room或Retrofit协同工作的项目示例.我只找到了Google的 ToDo示例,其中协程用于一次获取,然后手动重新获取数据在改变.

I would also like to see some examples of projects using coroutines and Flow to work with the Room or Retrofit. I found only a Google's ToDo sample where coroutines are used for one-shot fetching and then manually refetch data on changing.

推荐答案

Flow 是一种反应流(例如rxjava).有很多不同的运算符,例如 .map buffer()(无论如何,与rxJava相比,运算符的数量要少一些).因此, LiveData Flow 之间的主要区别之一是,您可以使用 computation/transform .>

Flow is sort of a reactive stream ( like rxjava ). There are a bunch of different operators like .map, buffer() ( anyway less no. Of operator compared to rxJava ). So, one of the main difference between LiveData and Flow is that u can subscribe the map computation / transformation in some other thread using

 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 时,上述方法无法直接实现!

With LiveData and map , the above cant be achieved directly !

因此,建议保持流在存储库级别,并使livedata成为UI和存储库之间的桥梁!

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

主要区别是 flow 有很多不同的运算符,而 livedata 没有!但是,再次取决于您,您要如何构建您的项目!

The main difference is that flow has got a bunch of different operators which livedata doesn't have ! But again , Its up to u how do u wanna construct your project !

这篇关于Kotlin Flow与LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆