ConflatedChannel

There is a third type of buffered channel, based on the idea that it's fine if elements that were emitted are lost. This means that this type of channel has a buffer of only one element, and whenever a new element is sent, the previous one will be lost. This also means that the sender will never be suspended.

You can instantiate it by calling its constructor:

val channel = ConflatedChannel<Int>()

You can also do so by calling the Channel() function with the parameter Channel.CONFLATED:

val channel = Channel<Int>(Channel.CONFLATED)

This channel will never suspend a sender. Instead, it will override the elements that were not retrieved. Consider this example:

fun main(args: Array<String>) = runBlocking {
val time = measureTimeMillis {
val channel = Channel<Int>(Channel.CONFLATED)
launch {
repeat(5) {
channel.send(it)
println("Sent $it")
}
}
delay(500)
val element = channel.receive()
println("Received $element")
}

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

This implementation will have element contain the last value that was sent through the channel. In this case, it will be the number four:

..................Content has been hidden....................

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