Channel channel of the coroutine in Kotlin (1)

tags: Kotlin coroutine  kotlin  android


Channel-channel

  • Channel is actually a secure queue, which can be used to connect corporations to achieve communication of different coroutines.
 @Test
    fun `test know channel`() = runBlocking<Unit> {
        val channel = Channel<Int>()
        // producer
        val producer = GlobalScope.launch {
            var i = 0
            while (true) {
                delay(1000)
                channel.send(++i)
                println("send $i")
            }
        }
        //consumer
        val consumer = GlobalScope.launch {
            while (true) {
                val element = channel.receive()
                println("receive $element")
            }
        }
        joinAll(producer, consumer)
    }

Channel capacity

  • Channel is actually a queue. There must be a buffer area in the queue. Once this buffer is full, no one has always called Receive and takes the function.
    Send needs to hang up. Drive the rhythm of the receiving end to slow down, and found that Send will always hang up until the Receive will continue to execute.
@Test
    fun `test know channel2`() = runBlocking<Unit> {
        val channel = Channel<Int>()
        // producer
        val producer = GlobalScope.launch {
            var i = 0
            while (true) {
                delay(1000)
                channel.send(++i)
                println("send $i")
            }
        }
        //consumer
        val consumer = GlobalScope.launch {
            while (true) {
                delay(2000)
                val element = channel.receive()
                println("receive $element")
            }
        }
        joinAll(producer, consumer)
    }

Iterate Channel

  • Channel itself is indeed like a sequence, so when we read, we can directly obtain a Channel's Iterator.
 @Test
    fun `test iterate channel`() = runBlocking<Unit> {
        val channel = Channel<Int>(Channel.UNLIMITED)
        // producer
        val producer = GlobalScope.launch {
            for (x in 1..5) {
                channel.send(x * x)
                println("send ${x * x}")
            }
        }
        //consumer
        val consumer = GlobalScope.launch {
            /*val iterator = channel.iterator()
            while (iterator.hasNext()){
                val element = iterator.next()
                println("receive $element")
                delay(2000)
            }*/
            for (element in channel) {
                println("receive $element")
                delay(2000)
            }
        }
        joinAll(producer, consumer)
    }

Produce and Actor

  • Constructing a convenient way for producers and consumers
  • We can start a producer coroutine through the Produce method and return a ReceiveChannel. Other corporates can use this Channel to receive the data.
    Conversely, we can use ACTOR to start a consumer corporation.
 @Test
    fun `test fast producer channel`() = runBlocking<Unit> {
        val receiveChannel: ReceiveChannel<Int> = GlobalScope.produce<Int> {
            repeat(100) {
                delay(1000)
                send(it)
            }
        }
        val consumer = GlobalScope.launch {
            for (i in receiveChannel) {
                println("received: $i")
            }
        }
        consumer.join()
    }

    @Test
    fun `test fast consumer channel`() = runBlocking<Unit> {
        val sendChannel: SendChannel<Int> = GlobalScope.actor<Int> {
            while (true) {
                val element = receive()
                println(element)
            }
        }
        val producer = GlobalScope.launch {
            for (i in 0..3) {
                sendChannel.send(i)
            }
        }
        producer.join()
    }

Channel's closure

  • The Channel returned by Produce and ACTOR will be closed as the corresponding coroutine is completed. It is also this that Channel is called a thermal data stream.
  • For a Channel, if we call its Close method, it will immediately stop receiving new elements, that is to say, at this time its iSCloseDForsnd will return True immediately. And because of the existence of the Channel buffer, there may be some elements that may not be processed at this time, so it is necessary to wait for all elements to be read after being read.
  • Channel's life cycle is best maintained by the leading party, and it is recommended that the leading party is closed.
@Test
    fun `test close channel`() = runBlocking<Unit> {
        val channel = Channel<Int>(3)
        // producer
        val producer = GlobalScope.launch {
            List(3) {
                channel.send(it)
                println("send $it")
            }
            channel.close()
            println(
                """close channel. 
                | -CloseForSend:${channel.isClosedForSend} 
                | -CloseForReceive: ${channel.isClosedForReceive}""".trimMargin()
            )
        }
        //consumer
        val consumer = GlobalScope.launch {
            for (element in channel) {
                println("receive $element")
                delay(1000)
            }
            println(
                """After Consuming. 
                | -CloseForSend:${channel.isClosedForSend} 
                | -CloseForReceive: ${channel.isClosedForReceive}""".trimMargin()
            )
        }
        joinAll(producer, consumer)
    }

BroadcastChannel

  • As mentioned earlier, there is a pair of situations in the Channel. From the perspective of data processing itself, although there are multiple receivers,
    However, the same element will only be read by one receiving end, and the broadcast is not the same. There is no mutual exclusion behavior in multiple receivers.
  @Test
    fun `test broadcast`() = runBlocking<Unit> {
//        val broadcastChannel = BroadcastChannel<Int>(Channel.BUFFERED)
        val channel = Channel<Int>()
        val broadcastChannel = channel.broadcast(3)
        val producer = GlobalScope.launch {
            List(3) {
                delay(100)
                broadcastChannel.send(it)
            }
            broadcastChannel.close()
        }
        List(3) { index ->
            GlobalScope.launch {
                val receiveChannel = broadcastChannel.openSubscription()
                for (i in receiveChannel) {
                    println("[#$index] received: $i")
                }
            }
        }.joinAll()
    }

Intelligent Recommendation

The most comprehensive KOTLIN cable: COROUTINE / CHANNEL / FLOW and practical applications

This concept begins in 1958, earlier than the thread, currently in many languages, Java does not have a native and trip, but you can use a large company yourself or use third-party libraries to suppor...

Swoole coroutine channel

bySwoole coroutine entry, to understand the basic writing of the coroutine. The specific point of is that it is an independent, non-execution task. What about tasks related to dependencies or executio...

Coroutine communication: channel Understanding

It has a function to do cumulative calculation, such as:...

Golang coroutine and channel arrangement

Coroutine goroutine It is not scheduled by the OS, but the user layer releases the CPU on its own, thereby switching between executive bodies. Go assists implementation at the bottom Involving system ...

go channel and coroutine

Coroutine InGo in,The concurrent processing part of the application is calledgoroutines(Coroutine) ,It can perform more efficient concurrent operations. The operating system will schedule threads to r...

More Recommendation

25. Learn Go Coroutine: Detailed Channel/Channel

Hi, everyone, I’m Brother Ming. During the time I was learning Golang, I wrote detailed study notes on my personal WeChat public account "Go Programming Time". For the Go language, I a...

Print 1-10 in order of Golang using coroutine and Channel sequence

Print 1-10 in order of Golang using coroutine and Channel sequence the whole idea A small point that needs to be noted code thanks the whole idea After a brief explanation, because the execution order...

NIO --- Channel Channel (1)

1. Simple overview of the channel: The channel is mainly used for the connection of the source node and the target node, and the Channel itself does not store the data, and it is necessary to cooperat...

Channel channel in Golang (1)

Channel channel in Golang (1) 1. Basic use of the Channel channel When the Channel channel is used, there are several attention points: 1. For goroutine, pass the message. Channel, each has associated...

Go language study notes (12) ------ coroutine (channel) and channel (channel)

First, concurrent, parallel and coroutine 1. Go The basic code blocks for building concurrent programs are gorouts and channels. They need language, compiler, and runtime support. The garbage collecto...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top