Creating a producer

To create a producer, the coroutine builder produce() must be called. It returns a ReceiveChannel<E>. Because producers are built on top of channels, to yield elements in a producer, you use the function send(E):

val producer = produce {
send(1)
}

It's possible to specify a CoroutineContext in the same way that you would with launch() or async():

val context = newSingleThreadContext("myThread")

val producer = produce(context) {
send(1)
}

Similar to iterators and sequences, you can specify a type, and it will work as long as the elements being emitted are compliant with it:

val producer : ReceiveChannel<Any> = produce(context) {
send(5)
send("a")
}
In chapter 6, Channels – Share Memory by Communicating, we will talk in more detail about channels, how they work, and how to use them.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.107.152