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

相关内容

热门资讯

领克车机系统安卓,安卓智能驾驶... 你有没有发现,现在开车的时候,车机系统越来越智能了?尤其是领克的安卓车机系统,简直让人爱不释手。今天...
安卓原生系统通知声音,定制个性... 你知道吗?手机里那些时不时冒出来的通知,有时候就像小精灵在耳边悄悄说话,有时候又像是闹钟在催你起床。...
安卓系统电脑键盘功能 你有没有发现,用安卓系统电脑打字的时候,键盘功能可真是丰富得让人眼花缭乱呢?今天,就让我带你一起探索...
安卓修改文件系统后缀,解锁文件... 你有没有想过,你的安卓手机里的文件系统后缀可以随意修改?听起来是不是有点神奇?没错,今天就来带你一探...
安卓系统多任务流转 你有没有发现,在使用安卓手机的时候,有时候会突然冒出一个任务流转的功能,让你瞬间切换到另一个应用,是...
神姬红包版安卓系统,解锁全新游... 你知道吗?最近在手机圈里,有个神姬红包版安卓系统可是火得一塌糊涂呢!这不,我就迫不及待地来和你聊聊这...
为什么国内要用安卓系统,探索国... 你知道吗?在国内,安卓系统可是占据了半壁江山呢!为什么国内要用安卓系统呢?这背后可是有着不少有趣的故...
htc安卓系统怎么升级8.0,... 亲爱的手机控们,你是否也像我一样,对手机系统升级充满了期待和好奇呢?尤其是当HTC安卓系统升级到8....
安卓系统最好的应用助手,助你轻... 你有没有发现,手机里那些乱糟糟的图标和复杂的设置让你头疼不已?别担心,今天我要给你介绍一个安卓系统里...
安卓系统如何下载teamhub... 你有没有想过,在安卓系统上下载一个叫做Teamhub的应用程序呢?这可是个超级实用的工具,无论是工作...
安卓系统如何看无线密码,安卓系... 你有没有想过,你的安卓手机是怎么看懂无线密码的呢?是不是觉得这背后藏着什么神秘的黑科技?别急,今天就...
pd13安装安卓系统,PD13... 你有没有想过,给你的PD13平板电脑装个全新的安卓系统,让它焕发第二春呢?想象那流畅的操作体验,那丰...
苹果系统怎么比安卓好,五大优势... 你有没有想过,为什么苹果系统那么多人喜欢,而安卓系统虽然普及,但总感觉少了点啥?今天,就让我来给你细...
苏州攻略系统和安卓互通,安卓互... 你打算去苏州游玩一番,是不是已经迫不及待想要探索这座古城的韵味了呢?别急,别急,让我来给你支支招,让...
安卓变苹果系统教程荣耀,安卓变... 你是不是也和我一样,对手机系统转换充满了好奇?想要从安卓跳到苹果的阵营,却又觉得一头雾水?别担心,今...
安卓115系统编写 你有没有听说啊?安卓115系统最近可是火得一塌糊涂!作为一个紧跟科技潮流的数码达人,我怎么能不给你来...
安卓系统内录怎么搞,轻松实现屏... 你有没有想过,在安卓手机上录制屏幕,那可是一项超实用的技能呢!无论是想记录游戏操作,还是制作教程,或...
国服无法进入安卓系统,安卓系统... 最近有没有发现,你的安卓手机上那些心仪的国服游戏突然变得高不可攀了呢?别急,让我来给你揭秘这背后的故...
安卓系统破解wifi密码破解,... 你是不是也和我一样,对破解WiFi密码这个话题充满了好奇?想象当你身处一个陌生的环境,急需上网却苦于...
安卓系统项目发布平台 你知道吗?在科技飞速发展的今天,安卓系统项目发布平台可是个香饽饽呢!它就像一个巨大的舞台,让无数开发...