Esa
01/27/2020, 8:32 AMtaskChannel
, a resultChannel
, a producer and multiple consumers. The producer is lightning fast and the consumers need a bit of time. Once the producer is done, it closes the taskChannel.
launch {
tasks.forEach {
taskChannel.send(it)
}
taskChannel.close()
}
Then this is the consumer side of things.
launch {
repeat (10) {
launch {
for (task in taskChannel) {
val result = process(task)
resultChannel.send(result)
}
}
}
}
This resultChannel undergoes one final step, which is logging the results:
for (result in resultChannel) {
log(result)
}
resultChannel.close()
My question is really just if I’ve closed the channels at the correct times etc. Also, is this a correct usage of the channels, or have I created some antipatterns or some such here? Any replies appreciated. It’s my first time looking into channels, and I like the way they let me start all three processes (production, consumption and logging) at the same timeDominaezzz
01/27/2020, 8:40 AMresultChannel
for loop looks suspicious. I reckon it will deadlock there. The channel as to be closed for the for loop to finish.Esa
01/27/2020, 8:42 AMlaunch
?Dominaezzz
01/27/2020, 8:44 AMrepeat
in a coroutineScope
and close the channel right after.Esa
01/27/2020, 8:50 AMDominaezzz
01/27/2020, 8:51 AMlaunch {
coroutineScope {
repeat (10) {
launch {
for (task in taskChannel) {
val result = process(task)
resultChannel.send(result)
}
}
}
}
resultChannel.close()
}
Esa
01/27/2020, 8:57 AMDominaezzz
01/27/2020, 12:08 PMEsa
01/27/2020, 12:15 PMrepeat() { launch { // this is a worker } }
section there.
Anything inside that launch I concider a workerDominaezzz
01/27/2020, 12:19 PMEsa
01/27/2020, 12:21 PMDominaezzz
01/27/2020, 12:30 PMtaskChannel
, don't send any tasks through, when you wish to pause.Esa
01/27/2020, 12:37 PM