Flow 简单使用
admin
2024-01-21 01:05:12
0

通过 Flow,我们可以以响应式的编程方式进行协程代码的编写。Flow 类似于协程版本的 RxJava,但是比起 RxJava,它会更加简单,更加容易上手。

基本使用

        GlobalScope.launch(Dispatchers.Main) {flow {repeat(3) { // 重复3次Thread.sleep(1000) //模拟耗时计算工作emit(it) // 发送结果}}.flowOn(Dispatchers.Default) // 切换到工作子线程.collect {// 运行在调用 collect 的线程当中,在此 case 中是 Dispatchers.Main,也就是主线程。Log.i("TAG", "it: $it") //打印 0 1 2}}

以上面的代码为例,我们使用 flow 主要有以下几步:
1.定义生产者函数,在函数中将结果通过 emit 函数发出。
2.如果需要指定生产者函数所运行的线程,通过 flowOn 函数指定并传入一个 CoroutineContext。
3.调用 collect 函数收集生产者函数的计算结果,collect 是一个 suspend 函数,运行在调用 collect 函数的线程当中,且在收集完成之前会一直挂起,因此需要在挂起函数中被调用。

操作符

flow 提供了非常丰富且便捷的操作符。

flowOn

用于指定生产者函数运行在哪个 CoroutineContext,如第一个例子所示。

onEach

每当生产者函数发送结果时,都会被调用。

    flow {repeat(3) {emit(it)}}.onEach {println("onEach $it") // 打印 0 1 2}.collect {println("collect $it") // 打印 0 1 2}

launchIn

指定在哪个 CoroutineContext 中进行收集,可以从源码中看出它的实现。

public fun  Flow.launchIn(scope: CoroutineScope): Job = scope.launch {collect() // tail-call
}

通过 launchIn,我们可以将第一个例子改成如下代码:

        GlobalScope.launch(Dispatchers.Main) {flow {repeat(3) { // 重复3次Thread.sleep(1000) //模拟耗时计算工作emit(it) // 发送结果}}.flowOn(Dispatchers.Default) // 切换到工作子线程.onEach {// 运行在调用 launchIn 的线程当中,在此 case 中是 Dispatchers.Main,也就是主线程。Log.i("TAG", "it: $it") //打印 0 1 2}.launchIn(this)}

onEmpty

当生产者函数没有发送任何结果时会被调用。

    flow { }.onEmpty { emit(-1) }.collect { println("testOnEmpty: $it") } // 打印 -1flow { emit(1) }.onEmpty { emit(-1) }.collect { println("testOnEmpty: $it") } // 打印 1

onStart

在收集开始之前调用

    // 打印 start 0 1 2flow {repeat(3) {emit(it)}}.onStart { println("start") }.collect { println("$it") }

onCompletion

在收集完成后调用

    // 打印 0 1 2 completion flow {repeat(3) {emit(it)}}.onCompletion { println("completion") }.collect { println("$it") } 

catch

当上游操作符或者生产者函数出现异常时被调用:

        // 打印// collect: 0// catch: java.lang.NullPointerExceptionflow {repeat(3) {if (it == 1) {throw NullPointerException()}emit(it)}}.catch { println("catch: $it") }.collect { println("collect: $it") }

map

将上游的结果进行变换后,发送给下游

        // 打印 0 1 4 9 16flow {repeat(5) {emit(it)}}.map { it * it }.collect { println("$it") }

flatMapConcat

根据上游 flow 的值生成新的 flow,再将新的 flow 的结果发送给下游收集者,下面是打印99乘法表的例子

        //打印//1 2 3 4 5 6 7 8 9//2 4 6 8 10 12 14 16 18//3 6 9 12 15 18 21 24 27//4 8 12 16 20 24 28 32 36//5 10 15 20 25 30 35 40 45//6 12 18 24 30 36 42 48 54//7 14 21 28 35 42 49 56 63//8 16 24 32 40 48 56 64 72//9 18 27 36 45 54 63 72 81flow {for (i in 1..9) {emit(i)}}.flatMapConcat {flow {for (j in 1..9) {emit(it * j)}println()}}.collect { print("$it ") }

collectLatest

当收集函数被挂起时,如果生产者函数发送了新结果,则取消当前被挂起的收集函数,并基于新结果重新运行收集函数。换句话说就是确保只接收最新的数据。

        //打印//0 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//1 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//2 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//3 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//4 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//5 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//6 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//7 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//8 kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled//9flow {repeat(10) {delay(100)emit(it)}}.collectLatest {try {delay(200)} catch (e: CancellationException) {println("$it $e")throw e}println("$it") //到这才算收集成功}

由于 collect 函数每次收集时都会挂起 200 毫秒,而生产函数每 100 毫秒就会发送一次数据,因此 collect 函数每次的挂起都会因为有新结果而被取消,直到最后一个数据发送时才能成功收集。

相关内容

热门资讯

122.(leaflet篇)l... 听老人家说:多看美女会长寿 地图之家总目录(订阅之前建议先查看该博客) 文章末尾处提供保证可运行...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
育碧GDC2018程序化大世界... 1.传统手动绘制森林的问题 采用手动绘制的方法的话,每次迭代地形都要手动再绘制森林。这...
Vue使用pdf-lib为文件... 之前也写过两篇预览pdf的,但是没有加水印,这是链接:Vu...
PyQt5数据库开发1 4.1... 文章目录 前言 步骤/方法 1 使用windows身份登录 2 启用混合登录模式 3 允许远程连接服...
Android studio ... 解决 Android studio 出现“The emulator process for AVD ...
Linux基础命令大全(上) ♥️作者:小刘在C站 ♥️个人主页:小刘主页 ♥️每天分享云计算网络运维...
再谈解决“因为文件包含病毒或潜... 前面出了一篇博文专门来解决“因为文件包含病毒或潜在的垃圾软件”的问题,其中第二种方法有...
南京邮电大学通达学院2023c... 题目展示 一.问题描述 实验题目1 定义一个学生类,其中包括如下内容: (1)私有数据成员 ①年龄 ...
PageObject 六大原则 PageObject六大原则: 1.封装服务的方法 2.不要暴露页面的细节 3.通过r...
【Linux网络编程】01:S... Socket多进程 OVERVIEWSocket多进程1.Server2.Client3.bug&...
数据结构刷题(二十五):122... 1.122. 买卖股票的最佳时机 II思路:贪心。把利润分解为每天为单位的维度,然后收...
浏览器事件循环 事件循环 浏览器的进程模型 何为进程? 程序运行需要有它自己专属的内存空间࿰...
8个免费图片/照片压缩工具帮您... 继续查看一些最好的图像压缩工具,以提升用户体验和存储空间以及网站使用支持。 无数图像压...
计算机二级Python备考(2... 目录  一、选择题 1.在Python语言中: 2.知识点 二、基本操作题 1. j...
端电压 相电压 线电压 记得刚接触矢量控制的时候,拿到板子,就赶紧去测各种波形,结...
如何使用Python检测和识别... 车牌检测与识别技术用途广泛,可以用于道路系统、无票停车场、车辆门禁等。这项技术结合了计...
带环链表详解 目录 一、什么是环形链表 二、判断是否为环形链表 2.1 具体题目 2.2 具体思路 2.3 思路的...
【C语言进阶:刨根究底字符串函... 本节重点内容: 深入理解strcpy函数的使用学会strcpy函数的模拟实现⚡strc...
Django web开发(一)... 文章目录前端开发1.快速开发网站2.标签2.1 编码2.2 title2.3 标题2.4 div和s...