diff --git a/kotlinx-coroutines-core/common/src/channels/Channel.kt b/kotlinx-coroutines-core/common/src/channels/Channel.kt index 3e3c0f5fae..8c4748e18d 100644 --- a/kotlinx-coroutines-core/common/src/channels/Channel.kt +++ b/kotlinx-coroutines-core/common/src/channels/Channel.kt @@ -1050,7 +1050,48 @@ public inline fun ChannelResult.onClosed(action: (exception: Throwable?) /** * Iterator for a [ReceiveChannel]. - * Instances of this interface are *not thread-safe* and shall not be used from concurrent coroutines. + * Instances of this interface are *not thread-safe*. + * A coroutine is only allowed to call methods on those iterator instances which it instantiated. + * + * Typically, an iterator is used indirectly in the `for` loop and is not instantiated explicitly. + * + * ``` + * for (element in channel) { + * // process the element + * } + * ``` + * + * If your use-case requires handling the iterator directly, + * you must call [hasNext] before each [next]. + * Refer to [hasNext] and [next] for more details. + * + * An example usage: + * + * ``` + * val channel = Channel() + * launch { + * channel.send(1) + * channel.send(2) + * channel.send(3) + * channel.close() // NB: must close for iterators to finish + * } + * launch { + * for (element in channel) { + * println("Consumer A got $element") + * } + * } + * launch { + * for (element in channel) { + * println("Consumer B got $element") + * } + * } + * ``` + * Possible output: + * ```text + * Consumer A got 1 + * Consumer A got 2 + * Consumer B got 3 + * ``` */ public interface ChannelIterator { /**