Is there an overload to `Channel.send()` where I c...
# coroutines
l
Is there an overload to
Channel.send()
where I can send multiple elements (instead of calling
send()
multiple times)?
s
Nope. I think the desired behaviour would be different from case to case, so that it would be hard to generalise a single implementation. For example, what would you do if the channel was closed part-way through adding the items?
l
True
My use case is that I send events from a ViewModel to the UI, that the UI should vibrate or play the sound etc.
Sometimes I want to send multiple events one after another.
But I will just do it using multiple
send()
functions
Copy code
with(_uiEventsChannel) {
    send(Vibrate)
    send(PlaySound)
    send(ShowToast(message))
}
j
You could implement your own naive extension that just loops over a collection of items and sends them one by one. Or create a compound event type that allows you to send a batch of events atomically
g
Or you could just write an extension function to compound them yourself:
Copy code
suspend fun <E> SendChannel<List<E>>.sendAll(vararg elements: E) = send(elements.toList())

suspend fun <E> ReceiveChannel<List<E>>.collectEach(block: FlowCollector<E>) = receiveAsFlow().collect { elements ->
    elements.forEach { 
        block.emit(it)
    }
}