asad.awadia
03/03/2019, 7:25 AMgroostav
03/03/2019, 7:53 PMI cant come out of a channel loopmeaning a for-each loop on a receive channel? Yeah, it only exits when the channel has completed. You might consider using a
withTimeoutOrNull
+ receieve
or select { channel.onReceieve {} ...
instead of a for-each loop if you need more control
Its a hard block on the executionCertainly not, the caller is suspended, and there's no execution in a channel per-se. Remember most of the time you wire a producer up to your channel that you're then consuming. When the consumer attempts to read an element it does so fully
asad.awadia
03/03/2019, 7:54 PMgroostav
03/03/2019, 7:58 PMbreak
?
for(element in foreverChannel){
if(state + element > threshold){
break;
}
}
?asad.awadia
03/03/2019, 7:58 PMgroostav
03/03/2019, 7:59 PMforeverChannel
, do you want it to cancel that channel?consumeEach
is what you want, and if thats true you can use the standard functional first
combinatorval result = foreverChannel.first { state + it > threshold }
foreverChannel
to be cancelled after the first element that matches that criteria, which causes your producers to all get signalled next time they try to produceasad.awadia
03/03/2019, 8:01 PMgroostav
03/03/2019, 8:08 PMtake(n)
that doesn't cancel the channel after receiving those elements.
quick point, you cantIf you think about your program as being a kind of parser then trying to look ahead on a channel some number of tokens (messages) without cancelling or closing the channel is totally reasonable.aclose
, you can onlyReceiveChannel
it. Producerscancel
the `SendChannel`s.close
Vsevolod Tolstopyatov [JB]
03/04/2019, 8:49 AMn
times and then returns without cancelling a channel (otherwise, you can use take
).
If you think this is a frequent use-case that keeps popping here and there, feel free to create an issue on github.suspend inline fun <E> ReceiveChannel<E>.iterate(limit: Int, action: suspend (element: E) -> Unit) {
var consumed = 0
for (element in this) {
action(element)
if (++consumed == limit) {
break
}
}
}
asad.awadia
03/04/2019, 5:59 PMgildor
03/05/2019, 1:39 AMasad.awadia
03/05/2019, 1:40 AMgildor
03/05/2019, 1:40 AMproduce
)val channel = produce {
while(true) {
send("something")
}
}
if you never close this channel it will leak coroutine and channel, but it’s not so bad, because now you can call produce only in CoroutineScope, this channel will be closed together with scope