当前位置:网站首页>Kotlin coordination channel
Kotlin coordination channel
2022-06-24 13:53:00 【day_ moon】
// 1. passageway Method of transmitting value stream fun main_channel() = runBlocking { val channel = Channel<Int>()// Make a statement channel launch { for (i in 1..3) { channel.send(i + i) }// send out 1+1 2+2 3+3 channel.close()// The channel is not closed immediately } repeat(3) { // It's OK to write like this for (y in channel) println(y) println(" What was received was ${channel.receive()}") } println("end ..") } //2. Build channel producers fun CoroutineScope.producer(): ReceiveChannel<Int> = produce {// Build channel producers for (i in 1..3) send(i + i) } fun main_produce() = runBlocking { val produce = producer() produce.consumeEach { println("$it") }// Iterate over each producer println("end ..") } //3 The Conduit fun CoroutineScope.produceNumbers(): ReceiveChannel<Int> = produce<Int> {// Every time add 1 Generate infinite No return type var x = 1 while (true) send(x++) } fun CoroutineScope.square(numbers: ReceiveChannel<Int>): ReceiveChannel<Int> = produce {// Received first , And then send it after processing for (x in numbers) send(x + x) } fun main_pip() = runBlocking { val numbers = produceNumbers() // Every time add 1 Generate infinite No return type val squares = square(numbers) // Received first , And then send it after processing repeat(3) {// repeat 3 Time println(squares.receive()) } println("end ..") // complete coroutineContext.cancelChildren() // Cancel subprocess } //4. The prime number of pipes fun main_filters() = runBlocking { var cur = numberssend(2)// Start with two 2 3 4.. repeat(10) {// take 10 Number val number = cur.receive() println(" $number") cur = filters(cur, number) } coroutineContext.cancelChildren() // cancel all children to let main finish } fun CoroutineScope.numberssend(start: Int) = produce<Int> {// Data is added every time 1 send out var x = start while (true) send(x++) } // from 2 Start a digital stream , Get a prime number from the current channel , And start a new pipeline for each prime number found fun CoroutineScope.filters(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> { for (x in numbers) if (x % prime != 0) send(x)// Can be divided by the number sent And then send } //5. Fan out fun mainFanout() = runBlocking<Unit> { val producer = produceNumber() repeat(5) { launchProcessor(it, producer) } delay(950) producer.cancel() // Cancel } fun CoroutineScope.produceNumber() = produce<Int> { var x = 1 while (true) { send(x++) // from 1 Start and add each time 1 delay(100) // } } fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { for (msg in channel) { println("Processor #$id received $msg") } } //6. Fan in fun main_in() = runBlocking { val channel = Channel<String>() // Two coroutines to send a string launch { sendString(channel, "foo", 200L) } launch { sendString(channel, "BAR!", 500L) } repeat(6) { // receive first six println(channel.receive()) } coroutineContext.cancelChildren() // cancel all children to let main finish } suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { while (true) { delay(time) channel.send(s) } } //7. Buffered channels fun main_Buffered() = runBlocking<Unit> { val channel = Channel<Int>(4) // Capacity of 4 val sender = launch { // Start the coroutines repeat(10) { println(" Data sent $it")//0-4 channel.send(it) } } delay(100)// Delay 1 second sender.cancel() // Cancel } //8. The channel is fair data class Ball(var hits: Int) fun main_fair() = runBlocking { val table = Channel<Ball>() // a shared table launch { player("ping", table) } launch { player("pong", table) } table.send(Ball(0)) // serve the ball delay(1000) // delay 1 second coroutineContext.cancelChildren() // game over, cancel them } suspend fun player(name: String, table: Channel<Ball>) { for (ball in table) { // receive the ball in a loop ball.hits++ println("$name $ball") delay(300) // wait a bit table.send(ball) // send the ball back } } //9. Timing channel fun main_Ticker() = runBlocking<Unit> { val tickerChannel = ticker(delayMillis = 100, initialDelayMillis = 0) // create ticker channel var nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } println("Initial element is available immediately: $nextElement") // initial delay hasn't passed yet nextElement = withTimeoutOrNull(50) { tickerChannel.receive() } // all subsequent elements has 100ms delay println("Next element is not ready in 50 ms: $nextElement") nextElement = withTimeoutOrNull(60) { tickerChannel.receive() } println("Next element is ready in 100 ms: $nextElement") // Emulate large consumption delays println("Consumer pauses for 150ms") delay(150) // Next element is available immediately nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } println("Next element is available immediately after large consumer delay: $nextElement") // Note that the pause between `receive` calls is taken into account and next element arrives faster nextElement = withTimeoutOrNull(60) { tickerChannel.receive() } println("Next element is ready in 50ms after consumer pause in 150ms: $nextElement") tickerChannel.cancel() // indicate that no more elements are needed }
边栏推荐
- Kotlin composite suspend function
- 详解kubernetes备份恢复利器 Velero | 深入了解Carina系列第三期
- 硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
- In the era of knowledge economy, it will teach you to do well in knowledge management
- 8 - Format integers and floating point numbers
- Operation of simulated examination platform for examination questions of coal production and operation units (safety production management personnel) in 2022
- 杰理之检测 MIC 能量自动录音自动播放参考【篇】
- 数学之英文写作——基本中英文词汇(几何与三角的常用词汇)
- HarmonyOS-3
- 《中国数据库安全能力市场洞察,2022》报告研究正式启动
猜你喜欢
位于相同的分布式端口组但不同主机上的虚拟机无法互相通信
如何避免严重网络安全事故的发生?
华为 PC 逆势增长,产品力决定一切
HarmonyOS. two
群晖向阿里云OSS同步
The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance
npm包【详解】(内含npm包的开发、发布、安装、更新、搜索、卸载、查看、版本号更新规则、package.json详解等)
【5G NR】5G NR系统架构
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
《中国数据库安全能力市场洞察,2022》报告研究正式启动
随机推荐
国内首款开源MySQL HTAP数据库即将发布,三大看点提前告知
kotlin 接口 泛型 协变 逆变
Gatling performance test
吉时利静电计宽测量范围
Coinbase will launch the first encryption derivative for individual investors
2022 construction elevator driver (construction special type of work) examination questions and online simulation examination
Kotlin anonymous function and lambda
Usage of multimeter
项目经理的晋级之路
杰理之无缝循环播放【篇】
Can a team do both projects and products?
万用表测量电阻图解及使用注意事项
【AI玩家养成记】用AI识别邻居家旺财是什么品种
Android kotlin Encyclopedia
Autorf: learn the radiation field of 3D objects from single view (CVPR 2022)
Seven challenges faced by data scientists and Solutions
Source code analysis handler interview classic
数据科学家面临的七大挑战及解决方法
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
npm包【详解】(内含npm包的开发、发布、安装、更新、搜索、卸载、查看、版本号更新规则、package.json详解等)