All Downloads are FREE. Search and download functionalities are using the official Maven repository.

channels.Produce.kt Maven / Gradle / Ivy

There is a newer version: 1.3.8
Show newest version
/*
 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines.channels

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlin.coroutines.*

/**
 * Scope for [produce] coroutine builder.
 */
public interface ProducerScope : CoroutineScope, SendChannel {
    /**
     * A reference to the channel that this coroutine [sends][send] elements to.
     * It is provided for convenience, so that the code in the coroutine can refer
     * to the channel as `channel` as apposed to `this`.
     * All the [SendChannel] functions on this interface delegate to
     * the channel instance returned by this function.
     */
    val channel: SendChannel
}

/**
 * @suppress **Deprecated**: Use `ReceiveChannel`.
 */
@Deprecated(message = "Use `ReceiveChannel`", replaceWith = ReplaceWith("ReceiveChannel"))
@Suppress("MULTIPLE_DEFAULTS_INHERITED_FROM_SUPERTYPES_WHEN_NO_EXPLICIT_OVERRIDE")
interface ProducerJob : ReceiveChannel, Job {
    @Deprecated(message = "Use ReceiveChannel itself")
    val channel: ReceiveChannel
}

/**
 * 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][ReceiveChannel.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][SendChannel.send] directly. The channel is [closed][SendChannel.close]
 * when the coroutine completes.
 * The running coroutine is cancelled when its receive channel is [cancelled][ReceiveChannel.cancel].
 *
 * The [context] for the new coroutine can be explicitly specified.
 * See [CoroutineDispatcher] for the standard context implementations that are provided by `kotlinx.coroutines`.
 * 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.
 *
 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [DefaultDispatcher] is used.
 *
 * 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:
 * * when `capacity` is 0 (default) -- uses [RendezvousChannel] without a buffer;
 * * when `capacity` is [Channel.UNLIMITED] -- uses [LinkedListChannel] with buffer of unlimited size;
 * * when `capacity` is [Channel.CONFLATED] -- uses [ConflatedChannel] that conflates back-to-back sends;
 * * when `capacity` is positive, but less than [UNLIMITED] -- uses [ArrayChannel] with a buffer of the specified `capacity`;
 * * otherwise -- throws [IllegalArgumentException].
 *
 * See [newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine.
 *
 * @param context context of the coroutine. The default value is [DefaultDispatcher].
 * @param capacity capacity of the channel's buffer (no buffer by default).
 * @param parent explicitly specifies the parent job, overrides job from the [context] (if any).*
 * @param onCompletion optional completion handler for the producer coroutine (see [Job.invokeOnCompletion]).
 * @param block the coroutine code.
 */
public fun  produce(
    context: CoroutineContext = DefaultDispatcher,
    capacity: Int = 0,
    parent: Job? = null,
    onCompletion: CompletionHandler? = null,
    block: suspend ProducerScope.() -> Unit
): ReceiveChannel {
    val channel = Channel(capacity)
    val newContext = newCoroutineContext(context, parent)
    val coroutine = ProducerCoroutine(newContext, channel)
    if (onCompletion != null) coroutine.invokeOnCompletion(handler = onCompletion)
    coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
    return coroutine
}

/** @suppress **Deprecated**: Binary compatibility */
@Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN)
public fun  produce(
    context: CoroutineContext = DefaultDispatcher,
    capacity: Int = 0,
    parent: Job? = null,
    block: suspend ProducerScope.() -> Unit
): ReceiveChannel = produce(context, capacity, parent, block = block)

/** @suppress **Deprecated**: Binary compatibility */
@Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN)
public fun  produce(
    context: CoroutineContext = DefaultDispatcher,
    capacity: Int = 0,
    block: suspend ProducerScope.() -> Unit
): ProducerJob =
    produce(context, capacity, block = block) as ProducerJob

/**
 * @suppress **Deprecated**: Renamed to `produce`.
 */
@Deprecated(message = "Renamed to `produce`", replaceWith = ReplaceWith("produce(context, capacity, block)"))
public fun  buildChannel(
    context: CoroutineContext,
    capacity: Int = 0,
    block: suspend ProducerScope.() -> Unit
): ProducerJob =
    produce(context, capacity, block = block) as ProducerJob

private class ProducerCoroutine(
    parentContext: CoroutineContext, channel: Channel
) : ChannelCoroutine(parentContext, channel, active = true), ProducerScope, ProducerJob {
    override fun onCancellationInternal(exceptionally: CompletedExceptionally?) {
        val cause = exceptionally?.cause
        val processed = when (exceptionally) {
            // producer coroutine was cancelled -- cancel channel, but without cause if it was closed without cause
            is Cancelled -> _channel.cancel(if (cause is CancellationException) null else cause)
            else -> _channel.close(cause) // producer coroutine has completed -- close channel
        }
        if (!processed && cause != null)
            handleCoroutineException(context, cause, this)
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy