LinkedListChannel

If you want a channel in which you are able to send an unlimited amount of elements without it suspending, then you need a LinkedListChannel. This type of channel will not suspend any senders. In order to instantiate this type of channel, you can use the constructor:

val channel = LinkedListChannel<Int>()

You can also use the Channel() function with the parameter Channel.UNLIMITED:

val channel = Channel<Int>(Channel.UNLIMITED)
Channel.UNLIMITED is equal to Int.MAX_VALUE, so sending either of them to Channel() will retrieve an instance of LinkedListChannel.

This channel will never suspend a sender. So for example consider the following code:

fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val channel = Channel<Int>(Channel.UNLIMITED)
val sender = launch {
repeat(5) {
println("Sending $it")
channel.send(it)
}
}

delay(500)
}

println("Took ${time}ms")
}

The previous implementation will allow sender to emit the five elements regardless of the channel not having any receiver to process them:

In reality, there is a limit for how many elements you can emit using LinkedListChannels, the memory. You have to be careful when using this type of channel because it may consume too much memory. It's recommended to use a buffered channel with a defined buffer size based on the requirements and the target devices instead of this.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.63