https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

Vlad

07/21/2020, 8:03 PM
Hello. Is there any simple build in extension to receive values from simple Channel like
Copy code
channel.consumeEach { }
but not close channel on cancel. consumeEach does not close BroadcastChannel nor ConflatedBroadcastChannel on cancelation. Should i just stick to
Copy code
for(it in channel){
    
}
and create my own helper extension function?
o

octylFractal

07/21/2020, 8:05 PM
I don't quite get the question, do you want it to close on cancel or not? you said "Is there .... like
consumeEach
, but does not close on cancel", but also "`consumeEach` does not close on cancel", which makes it sound like you already have what you want
v

Vlad

07/21/2020, 8:12 PM
Example
Copy code
val channel = Channel<Int>(capacity = 1)
val broadcastChannel = BroadcastChannel<Int>(capacity = 1)

launch { channel.consumeEach { } }.apply {
    delay(100)
    cancel()
}
launch { broadcastChannel.consumeEach { } }.apply {
    delay(100)
    cancel()
}
println("${channel.isClosedForReceive} ${channel.isClosedForReceive}")
println("${broadcastChannel.isClosedForSend}")
output
Copy code
false false
true
I want it to stay alive and use reuse it sometime later
o

octylFractal

07/21/2020, 8:13 PM
is there something wrong with using the
for
loop? I think that's basically what you want, and it isn't much longer than a method call
If you need to iterate over the channel without consuming it, a regular
for
loop should be used instead.
2 Views