aarkling
08/17/2023, 1:33 AMsuspend fun main() = coroutineScope {
val channel = Channel<Int>()
//channel.close()
launch {
println("closing")
channel.close()
}
channel.send(0) // hangs forever!!
println("end")
}
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS45LjAiLCJwbGF0Zm9ybSI6ImphdmEiLCJhcmdzIj[…]FubmVsLnNlbmQoMClcbiAgICBwcmludGxuKFwiZW5kXCIpXG59XG4ifQ==aarkling
08/17/2023, 1:35 AMaarkling
08/17/2023, 2:23 AMSam
08/17/2023, 7:52 AMsend
, which I think does a good job of explaining what’s going on here.
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.If you want to immediately drop all elements from the channel and cancel any attempts to send new elements, you should call
cancel
instead of close
. The close function is for use by the sender, and the cancel function is for use by the receiver.aarkling
08/17/2023, 5:24 PMconsumeAsFlow
. I accepted you answer though and posted a different question.aarkling
08/17/2023, 5:26 PMSam
08/17/2023, 5:36 PMconsumeAsFlow
just creates the flow, it doesn't run it. You need to call a terminal function like collect
(or launchIn
) to have the flow actually execute.aarkling
08/17/2023, 5:43 PMaarkling
08/17/2023, 5:43 PMaarkling
08/17/2023, 7:17 PM