Dmytro Serdiuk
01/16/2024, 2:46 PMCancels reception of remaining elements from this channel with an optional cause. This function closes the channel and removes all buffered sent elements from it.Closing a channel after this function has suspended does not cause this suspended send invocation to abort, because closing a channel is conceptually like sending a special "close token" over this channel. All elements sent over the channel are delivered in first-in first-out order. The sent element will be delivered to receivers before the close token.Sam
01/16/2024, 3:50 PMclose()SendChannelcancel()ReceiveChannelSam
01/16/2024, 3:50 PMDmytro Serdiuk
01/16/2024, 3:53 PMval t = Channel<Int>(capacity = 0) { element ->
    println("Clean up element ${element}")
}
fun main() = runBlocking<Unit> { //sampleStart
    
    withTimeout(500) {
        val s = launch(newSingleThreadContext("S Coroutine")) {
        println("I'm inside === ${Thread.currentThread()}")
        delay(50)
        println("Before send === ${Thread.currentThread()}")
        try {
            t.send(4)
        } catch(e: Throwable) {
            println("Send finished with ${e} === ${Thread.currentThread()}")
            println(t.isClosedForReceive)
        }
        println("Finished send")
    }
    
    launch(newSingleThreadContext("Cancel Coroutine")) {
        println("Before cancel === ${Thread.currentThread()}")
        delay(90)
        println("Will cancel === ${Thread.currentThread()}")
        t.cancel()
        println(t.isClosedForSend)
    }
    
    launch(newSingleThreadContext("Check Coroutine")) {
        println("Before receive delay === ${Thread.currentThread()}")
        delay(150)
        println("Before receive === ${Thread.currentThread()}")
        try {
            val value1 = t.receive()
            
            println("Receive finished with ${value1} === ${Thread.currentThread()}")
            println(t.isClosedForReceive)
        } catch(e: Throwable) {
            println("Receive finished with ${e} === ${Thread.currentThread()}")
        }
        println("Received finished === ${Thread.currentThread()}")
    }
    }
//sampleEnd
}Sam
01/16/2024, 4:01 PMcancel()close()isClosedForSendtruesendclose()cancel()Dmytro Serdiuk
01/16/2024, 4:02 PM