当前位置: 首页 > news >正文

Kotlin协程Flow流buffer缓冲批量任务或数据,条件筛选任务或数据

Kotlin协程Flow流buffer缓冲批量任务或数据,条件筛选任务或数据

import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.runBlockingfun main() {runBlocking {var eachFlag = truevar collectFlag = true(0..50).chunked(5) //切块,分区.asFlow().onStart { println("onStart") }.onEach { itList ->//假设这里是生产者,密集生产数据或任务collectFlag = trueif (eachFlag) {println("--------------------")eachFlag = false}print("onEach [ ")itList.forEach { itData ->print("$itData ")}print("]")println()}.buffer(capacity = 3, onBufferOverflow = BufferOverflow.SUSPEND).collect { itList ->//假设这里是消费者,这里的消费者以一定的耗时完成任务或消费数据eachFlag = trueif (collectFlag) {println("↓")collectFlag = false}print("collect [ ")itList.forEach { itData ->print("$itData ")}print("]")val sortedList = itList.sortedBy { it }print(" 最大值=${sortedList.lastOrNull()} 最小值=${sortedList.firstOrNull()}")println()}}
}

输出:

onStart
--------------------
onEach [ 0 1 2 3 4 ]
onEach [ 5 6 7 8 9 ]
onEach [ 10 11 12 13 14 ]
onEach [ 15 16 17 18 19 ]
onEach [ 20 21 22 23 24 ]

collect [ 0 1 2 3 4 ] 最大值=4 最小值=0
collect [ 5 6 7 8 9 ] 最大值=9 最小值=5
collect [ 10 11 12 13 14 ] 最大值=14 最小值=10
collect [ 15 16 17 18 19 ] 最大值=19 最小值=15
collect [ 20 21 22 23 24 ] 最大值=24 最小值=20
--------------------
onEach [ 25 26 27 28 29 ]
onEach [ 30 31 32 33 34 ]
onEach [ 35 36 37 38 39 ]
onEach [ 40 41 42 43 44 ]
onEach [ 45 46 47 48 49 ]

collect [ 25 26 27 28 29 ] 最大值=29 最小值=25
collect [ 30 31 32 33 34 ] 最大值=34 最小值=30
collect [ 35 36 37 38 39 ] 最大值=39 最小值=35
collect [ 40 41 42 43 44 ] 最大值=44 最小值=40
collect [ 45 46 47 48 49 ] 最大值=49 最小值=45
--------------------
onEach [ 50 ]

collect [ 50 ] 最大值=50 最小值=50

相关:

https://blog.csdn.net/zhangphil/article/details/132527122

https://blog.csdn.net/zhangphil/article/details/139237348

http://www.dtcms.com/a/609863.html

相关文章:

  • BuildingAI 控制台智能体菜单和页面功能PRD
  • 球机与云台摄像机的差异解析
  • Opencv(十二):图像矫正
  • Muon 优化器:通过正交化动量矩阵革命性地加速 AI 大模型训练
  • 11.14 脚本网页游戏 猜黑红
  • 网站引导页的作用网络营销msn是什么
  • 余姚网站开发wordpress头像同步
  • vxe-table 配置 ajax 加载列表数据,配置分页和查询搜索表单
  • worldpress 建站直播app定制开发
  • Java IDEA学习之路:第九周课程笔记归纳
  • Node.js 配置管理:生物启发式系统与跨维度架构
  • 《强量化 Transformers:开启计算机视觉新篇》
  • 免费做店招的网站国外用wordpress
  • 网站制作器手机版北京网页设计制作
  • 互联网服务的全链路架构流程解析
  • ARM与x86交叉编译实战排错指南
  • Agentic RL 如何让语⾔ 模型成为⾃主智能体
  • k8s之Headless浅谈
  • 安卓Telephony中的 phoneId、subId、simSlotIndex含义对比
  • dw做的网站怎么传到网络上去哪里有做ppt模板下载网站
  • 快速建站费用wordpress 注册简码
  • 从出厂到交付:能源设备运输如何实现全程风险可视化?
  • Kubernetes环境部署Redis集群
  • 公司门禁使用操作说明书
  • Wireshark网络数据包分析工具完整教程与实战案例
  • 以往届优秀展商为镜,探2026航空发动机与燃气轮机展——新奥能源
  • 先买空间再写网站广州番禺伤人案
  • 人工智能之数据分析 numpy:第二章 简介与安装
  • 地图可视化实践录:使用Turf.js简化路线
  • 从零开始搭建Linux Web服务器