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

Marc Knaup

12/13/2018, 4:03 PM
Is there a quick way to create a
ReceiveChannel
from an
Iterable
? à la
Copy code
fun <E> Iterable<E>.toChannel() =
	GlobalScope.produce { forEach { send(it) } }
m

mbonnet

12/13/2018, 4:30 PM
Hey, I came up with this :
Copy code
fun <T> Iterable<T>.toChannel(): ReceiveChannel<T> {
    val channel = Channel<T>(Channel.UNLIMITED)
    GlobalScope.launch {
        this@toChannel.forEach { channel.send(it) }
        channel.close()
    }
    return channel
}
I only tested it on a quick example, seems to work ok !
m

Marc Knaup

12/13/2018, 4:39 PM
Thanks! Is there a difference between the two?
d

Dico

12/13/2018, 5:20 PM
I think
produce
might use a different type of channel. Other than that, produce vs. launch.
5 Views