Skip to content

Commit cdc5865

Browse files
fvascoelizarov
authored andcommitted
SendChannel.sendBlocking extension method
1 parent eb98bc8 commit cdc5865

File tree

1 file changed

+19
-0
lines changed
  • core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels

1 file changed

+19
-0
lines changed

core/kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/channels/Channels.kt

+19
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package kotlinx.coroutines.experimental.channels
1818

19+
import kotlinx.coroutines.experimental.runBlocking
20+
1921
internal const val DEFAULT_CLOSE_MESSAGE = "Channel was closed"
2022

2123
/**
@@ -47,3 +49,20 @@ public inline suspend fun <E> BroadcastChannel<E>.consumeEach(action: (E) -> Uni
4749
@Deprecated("binary compatibility with old code", level = DeprecationLevel.HIDDEN)
4850
public suspend fun <E> BroadcastChannel<E>.consumeEach(action: suspend (E) -> Unit) =
4951
consumeEach { action(it) }
52+
53+
/**
54+
* Adds [element] into to this channel, **blocking** the caller while this channel [Channel.isFull],
55+
* or throws exception if the channel [Channel.isClosedForSend] (see [Channel.close] for details).
56+
*
57+
* This is a way to call [Channel.send] method inside a blocking code using [runBlocking],
58+
* so this function should not be used from coroutine.
59+
*/
60+
public fun <E> SendChannel<E>.sendBlocking(element: E) {
61+
// fast path
62+
if (offer(element))
63+
return
64+
// slow path
65+
runBlocking {
66+
send(element)
67+
}
68+
}

0 commit comments

Comments
 (0)