produce

@ExperimentalCoroutinesApi fun <E> CoroutineScope.produce(
    context: CoroutineContext = EmptyCoroutineContext,
    capacity: Int = 0,
    block: suspend ProducerScope<E>.() -> Unit
): ReceiveChannel<E>
(source)

Launches a new coroutine to produce a stream of values by sending them to a channel and returns a reference to the coroutine as a ReceiveChannel. This resulting object can be used to receive elements produced by this coroutine.

The scope of the coroutine contains the ProducerScope interface, which implements both CoroutineScope and SendChannel, so that the coroutine can invoke send directly. The channel is closed when the coroutine completes. The running coroutine is cancelled when its receive channel is cancelled.

The coroutine context is inherited from this CoroutineScope. Additional context elements can be specified with the context argument. If the context does not have any dispatcher or other ContinuationInterceptor, then Dispatchers.Default is used. The parent job is inherited from the CoroutineScope as well, but it can also be overridden with a corresponding context element.

Any uncaught exception in this coroutine will close the channel with this exception as the cause and the resulting channel will become failed, so that any attempt to receive from it thereafter will throw an exception.

The kind of the resulting channel depends on the specified capacity parameter. See the Channel interface documentation for details.

See newCoroutineContext for a description of debugging facilities available for newly created coroutines.

Note: This is an experimental api. Behaviour of producers that work as children in a parent scope with respect to cancellation and error handling may change in the future.

Parameters

context - additional to CoroutineScope.coroutineContext context of the coroutine.

capacity - capacity of the channel’s buffer (no buffer by default).

block - the coroutine code.