I wrote this simple extension function to endlessl...
# coroutines
d
I wrote this simple extension function to endlessly subscribe to a channel (the subscriber’s scope is always <= the sender’s scope):
Copy code
internal suspend fun <E> ReceiveChannel<E>.forEach(action: (E) -> Unit) {
    val iterator = iterator()
    while (iterator.hasNext())
        action.invoke(iterator.next())
}
I was surprised that such an extension didn’t already exist—things like
consumeEach
only consume existing items in the Channel and then cancel. Am I either missing a function that does what I want, or missing a reason that I shouldn’t do this?
d
consumeEach
is intended to be used as the sole consumer of a channel. there is little wrong with
for (item in channel){}
and your code is doing exactly that but without syntactic sugar.
☝🏼 3
d
Channels don't have subscribers.
d
OH. It clicks now. Thanks y’all!