https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Drew Hamilton

01/20/2020, 4:18 PM
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

Dico

01/20/2020, 4:28 PM
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

Dominaezzz

01/20/2020, 4:28 PM
Channels don't have subscribers.
d

Drew Hamilton

01/20/2020, 6:34 PM
OH. It clicks now. Thanks y’all!
2 Views