fun <E> CoroutineScope.produce((source)
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = 0,
onCompletion: CompletionHandler? = null,
block: suspend ProducerScope<E>.() -> Unit
Launches 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 ProducerScope interface, which implements both CoroutineScope and SendChannel, so that coroutine can invoke send directly. The channel is closed when the coroutine completes. The running coroutine is cancelled when its receive channel is cancelled.
Coroutine context is inherited from a CoroutineScope, additional context elements can be specified with context argument. If the context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used. The parent job is inherited from a CoroutineScope as well, but it can also be overridden with corresponding coroutineContext element.
Uncaught exceptions in this coroutine close the channel with this exception as a cause and the resulting channel becomes failed, so that any attempt to receive from such a channel throws exception.
The kind of the resulting channel depends on the specified capacity parameter:
capacityis 0 (default) – uses RendezvousChannel without a buffer;
capacityis Channel.UNLIMITED – uses LinkedListChannel with buffer of unlimited size;
capacityis Channel.CONFLATED – uses ConflatedChannel that conflates back-to-back sends;
capacityis positive, but less than UNLIMITED – uses ArrayChannel with a buffer of the specified
- otherwise – throws IllegalArgumentException.
See newCoroutineContext for a description of debugging facilities that are available for newly created coroutine.
context - additional to CoroutineScope.coroutineContext context of the coroutine.
capacity - capacity of the channel’s buffer (no buffer by default).
onCompletion - optional completion handler for the producer coroutine (see Job.invokeOnCompletion).
block - the coroutine code.