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 函数每次的挂起都会因为有新结果而被取消,直到最后一个数据发送时才能成功收集。

相关内容

热门资讯

【MySQL】锁 锁 文章目录锁全局锁表级锁表锁元数据锁(MDL)意向锁AUTO-INC锁...
【内网安全】 隧道搭建穿透上线... 文章目录内网穿透-Ngrok-入门-上线1、服务端配置:2、客户端连接服务端ÿ...
GCN的几种模型复现笔记 引言 本篇笔记紧接上文,主要是上一篇看写了快2w字,再去接入代码感觉有点...
数据分页展示逻辑 import java.util.Arrays;import java.util.List;impo...
Redis为什么选择单线程?R... 目录专栏导读一、Redis版本迭代二、Redis4.0之前为什么一直采用单线程?三、R...
【已解决】ERROR: Cou... 正确指令: pip install pyyaml
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
Lock 接口解读 前置知识点Synchronized synchronized 是 Java 中的关键字,...
Win7 专业版安装中文包、汉... 参考资料:http://www.metsky.com/archives/350.htm...
3 ROS1通讯编程提高(1) 3 ROS1通讯编程提高3.1 使用VS Code编译ROS13.1.1 VS Code的安装和配置...
大模型未来趋势 大模型是人工智能领域的重要发展趋势之一,未来有着广阔的应用前景和发展空间。以下是大模型未来的趋势和展...
python实战应用讲解-【n... 目录 如何在Python中计算残余的平方和 方法1:使用其Base公式 方法2:使用statsmod...
学习u-boot 需要了解的m... 一、常用函数 1. origin 函数 origin 函数的返回值就是变量来源。使用格式如下...
常用python爬虫库介绍与简... 通用 urllib -网络库(stdlib)。 requests -网络库。 grab – 网络库&...
药品批准文号查询|药融云-中国... 药品批文是国家食品药品监督管理局(NMPA)对药品的审评和批准的证明文件...
【2023-03-22】SRS... 【2023-03-22】SRS推流搭配FFmpeg实现目标检测 说明: 外侧测试使用SRS播放器测...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
初级算法-哈希表 主要记录算法和数据结构学习笔记,新的一年更上一层楼! 初级算法-哈希表...
进程间通信【Linux】 1. 进程间通信 1.1 什么是进程间通信 在 Linux 系统中,进程间通信...
【Docker】P3 Dock... Docker数据卷、宿主机与挂载数据卷的概念及作用挂载宿主机配置数据卷挂载操作示例一个容器挂载多个目...