Actually i got very similar output when i use throw cancellationException or channel.cancel(). The working both similar close channel and cancel the receiving side .what the difference can any one explain . so that anyone understand
Code
suspend fun hello(){
val channel = Channel<Int>()
val sender = CoroutineScope(Dispatchers.Default).launch {
try{
for (i in 1..6){
if(this.isActive){
println("sending $i")
channel.send(i)
}
}
}catch (e : Exception){
println("exception is caught in send side $e")
}
}
sender.invokeOnCompletion { it ->
if(it == null){
println("sender complete successfully")
}
else if(it == CancellationException()){
println("sender was cancelled")
}
else {
println("sender failed")
}
}
val recieve = CoroutineScope(Dispatchers.Default).launch {
try {
channel.consume {
for (i in this) {
if(coroutineContext.isActive){
if(i == 2){
// channel.cancel()
throw CancellationException()
}
println("received $i")
}
}
}
}catch(ex : Exception){
println("exception is caught in receive side $ex")
}
}
channel.invokeOnClose {
println("channel has closed do some clean up")
}
recieve.invokeOnCompletion {
if(it == null){
println("receiver complete successfully")
}
else if(it == CancellationException()){
println("receiver was cancelled")
}
else{
println("receiver failed")
}
}
sender.join()
recieve.join()
}
Output when i cancel()
sending 1
sending 2
received 1
sending 3
channel has closed do some clean up
received 2
exception is caught in send side java.util.concurrent.CancellationException: Channel was cancelled
sender complete successfully
exception is caught in receive side java.util.concurrent.CancellationException: Channel was cancelled
receiver complete successfully
I get Output when i use throw Cancellation Exception
sending 1
sending 2
received 1
sending 3
channel has closed do some clean up
exception is caught in receive side java.util.concurrent.CancellationException
exception is caught in send side java.util.concurrent.CancellationException
receiver complete successfully
sender complete successfully