fun <E> produce(
context: CoroutineContext = DefaultDispatcher,
capacity: Int = 0,
parent: Job? = null,
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.
The context for the new coroutine can be explicitly specified.
See CoroutineDispatcher for the standard context implementations that are provided by
The coroutineContext of the parent coroutine may be used,
in which case the Job of the resulting coroutine is a child of the job of the parent coroutine.
The parent job may be also explicitly specified using parent parameter.
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 - context of the coroutine. The default value is DefaultDispatcher.
capacity - capacity of the channel’s buffer (no buffer by default).
parent - explicitly specifies the parent job, overrides job from the context (if any).*
onCompletion - optional completion handler for the producer coroutine (see Job.invokeOnCompletion).
block - the coroutine code.