The producer function

The producer function is called a channel builder, and it returns an instance of the ReceiveChannel class. This function looks as follows:

@ExperimentalCoroutinesApi
public fun <E> CoroutineScope.produce(
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = 0,
block: suspend ProducerScope<E>.() -> Unit
): ReceiveChannel<E> {
val channel = Channel<E>(capacity)
val newContext = newCoroutineContext(context)
val coroutine = ProducerCoroutine(newContext, channel)
coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
return coroutine
}

As you can see in the preceding snippet, the produce function contains a receiver parameter of the ProducerScope type. The ProducerScope interface looks as follows:

public interface ProducerScope<in E> : CoroutineScope, SendChannel<E> {
val channel: SendChannel<E>
}

As you can see, the ProducerScope interface extends the SendChannel interface. This means that we can use the send method inside a lambda that we pass to the producer function.

An example of using the  producer function may look as follows:

suspend fun numbersProduce(): ReceiveChannel<Int> = GlobalScope.produce {
launch {
(0..10).forEach {
send(it)
}
}
}

We can use the numbersProduce function in the following way:

fun producerExample() = runBlocking<Unit> {
val numbers = numbersProduce()
for (value in numbers) {
println(value)
}
}
..................Content has been hidden....................

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