louiscad
08/14/2018, 2:06 PMwithoutclass
08/14/2018, 2:06 PMMartin Devillers
08/14/2018, 2:12 PMwithoutclass
08/14/2018, 2:34 PMinternal suspend fun batchEvents(inChannel: ReceiveChannel<Unit>,
outChannel: SendChannel<List<Unit>>) {
while (isActive) {
delay(UPDATE_INTERVAL)
val accumulator = mutableListOf<Unit>()
while (!inChannel.isEmpty) {
val event = inChannel.receive()
accumulator.add(packet)
}
outChannel.send(accumulator)
accumulator.clear()
}
}
Martin Devillers
08/14/2018, 2:46 PMReceiveChannel<List<T>>
. That loop should suspend until at least one item is available, then return the batch of all the elements received from the ReceiveChannel<T>
since the last iteration.
So regarding your comment
What I’m saying is your if condition there will probably never trigger because the for loop will not run if it’s emptyI don’t want the for loop to run if it’s empty, because in that case there’s nothing to handle in a batch. It should wait until a non-empty batch is available.
withoutclass
08/14/2018, 2:54 PMyield()
so that it cooperates with other things running on the dispatcherMartin Devillers
08/14/2018, 3:21 PM@Test
fun test() {
val channel = Channel<Int>(Channel.UNLIMITED)
val batched = channel.batched(Unconfined)
val batches = mutableListOf<List<Int>>()
launch(Unconfined) {
for (it in 1..3) { channel.send(it) }
batches += batched.receive()
for (it in 4..6) { channel.send(it) }
batches += batched.receive()
batches += batched.receive()
}
assertEquals(listOf(listOf(1), listOf(2, 3), listOf(4, 5, 6)), batches)
}
It passes. I actually had to fix one one thing, because the batched channel needed to be a rendez-vous channel. So the for loop doesn’t seem to be an issue. Your example should also work I think, but I’m not sure that it improves anything (I was looking for maybe a more “direct” solution).withoutclass
08/14/2018, 3:29 PMMartin Devillers
08/14/2018, 3:30 PM