1
1
/*
2
- * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
2
+ * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3
3
*/
4
4
5
5
package kotlinx.coroutines.channels
@@ -13,6 +13,7 @@ import kotlin.coroutines.intrinsics.*
13
13
14
14
/* *
15
15
* Broadcasts all elements of the channel.
16
+ * This function [consumes][ReceiveChannel.consume] all elements of the original [ReceiveChannel].
16
17
*
17
18
* The kind of the resulting channel depends on the specified [capacity] parameter:
18
19
* when `capacity` is positive (1 by default), but less than [UNLIMITED] -- uses `ArrayBroadcastChannel` with a buffer of given capacity,
@@ -28,7 +29,12 @@ fun <E> ReceiveChannel<E>.broadcast(
28
29
): BroadcastChannel <E > =
29
30
GlobalScope .broadcast(Dispatchers .Unconfined , capacity = capacity, start = start, onCompletion = consumes()) {
30
31
for (e in this @broadcast) {
31
- send(e)
32
+ try {
33
+ send(e)
34
+ } catch (e: ClosedSendChannelException ) {
35
+ // the resulting BroadcastChannel was closed -> just break the sending loop
36
+ break
37
+ }
32
38
}
33
39
}
34
40
@@ -119,6 +125,13 @@ private open class BroadcastCoroutine<E>(
119
125
val processed = _channel .close(cause)
120
126
if (! processed && ! handled) handleCoroutineException(context, cause)
121
127
}
128
+
129
+ // The BroadcastChannel could be also closed
130
+ override fun close (cause : Throwable ? ): Boolean {
131
+ val result = _channel .close(cause)
132
+ cancelCoroutine(cause)
133
+ return result
134
+ }
122
135
}
123
136
124
137
private class LazyBroadcastCoroutine <E >(
0 commit comments