当前位置:网站首页>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
}边栏推荐
- Prometheus pushgateway
- 居家办公更要高效-自动化办公完美提升摸鱼时间 | 社区征文
- Kotlin coroutine context and scheduler
- Dragon lizard developer said: first time you got an electric shock, so you are such a dragon lizard community| Issue 8
- kotlin 协程上下文和调度器
- 位于相同的分布式端口组但不同主机上的虚拟机无法互相通信
- HarmonyOS-3
- Talk about GC of JVM
- 这几个默认路由、静态路由的配置部署都不会,还算什么网工!
- 【sdx62】WCN685X IPA不生效问题分析及解决方案
猜你喜欢

How to manage tasks in the low code platform of the Internet of things?
![[R language data science] (XIV): random variables and basic statistics](/img/87/3606041a588ecc615eb8013cdf9fb1.png)
[R language data science] (XIV): random variables and basic statistics

华为 PC 逆势增长,产品力决定一切

The research on the report "market insight into China's database security capabilities, 2022" was officially launched

AutoRF:从单视角观察中学习3D物体辐射场(CVPR 2022)

Gatling 性能测试

《中国数据库安全能力市场洞察,2022》报告研究正式启动

10 个 Reduce 常用“奇技淫巧”

如何避免严重网络安全事故的发生?

Home office should be more efficient - automated office perfectly improves fishing time | community essay solicitation
随机推荐
Use of kotlin arrays, collections, and maps
kotlin 协程 lanch 详解
MIT-6.824-lab4A-2022(万字讲解-代码构建)
[R language data science] (XIV): random variables and basic statistics
详解kubernetes备份恢复利器 Velero | 深入了解Carina系列第三期
Goldfish rhca memoirs: do447 manage lists and credentials -- create machine credentials for the access list host
The research on the report "market insight into China's database security capabilities, 2022" was officially launched
Cloud native essay solicitation progress case practice
Vulnerability management mistakes that CIOs still make
杰理之TIMER0 用默认的 PA13 来检测脉宽【篇】
[5g NR] 5g NR system architecture
Operation of simulated examination platform for examination questions of coal production and operation units (safety production management personnel) in 2022
杰理之检测 MIC 能量自动录音自动播放参考【篇】
黄楚平主持召开定点联系珠海工作视频会议 坚决落实省委部署要求 确保防疫情、稳经济、保安全取得积极成效
【AI玩家养成记】用AI识别邻居家旺财是什么品种
10 reduce common "tricks"
Docker安装redis
项目经理搭建团队,需要看6个特征
Vim 常用快捷键
Source code analysis handler interview classic