-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathChannel.kt
1486 lines (1432 loc) · 67.7 KB
/
Channel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@file:Suppress("FunctionName")
package kotlinx.coroutines.channels
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel.Factory.BUFFERED
import kotlinx.coroutines.channels.Channel.Factory.CHANNEL_DEFAULT_CAPACITY
import kotlinx.coroutines.channels.Channel.Factory.CONFLATED
import kotlinx.coroutines.channels.Channel.Factory.RENDEZVOUS
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.internal.*
import kotlinx.coroutines.selects.*
import kotlin.contracts.*
import kotlin.internal.*
import kotlin.jvm.*
/**
* Sender's interface to a [Channel].
*
* Combined, [SendChannel] and [ReceiveChannel] define the complete [Channel] interface.
*
* It is not expected that this interface will be implemented directly.
* Instead, the existing [Channel] implementations can be used or delegated to.
*/
public interface SendChannel<in E> {
/**
* Returns `true` if this channel was closed by an invocation of [close] or its receiving side was [cancelled][ReceiveChannel.cancel].
* This means that calling [send] will result in an exception.
*
* Note that if this property returns `false`, it does not guarantee that a subsequent call to [send] will succeed,
* as the channel can be concurrently closed right after the check.
* For such scenarios, [trySend] is the more robust solution: it attempts to send the element and returns
* a result that says whether the channel was closed, and if not, whether sending a value was successful.
*
* ```
* // DANGER! THIS CHECK IS NOT RELIABLE!
* if (!channel.isClosedForSend) {
* channel.send(element) // can still fail!
* } else {
* println("Can not send: the channel is closed")
* }
* // DO THIS INSTEAD:
* channel.trySend(element).onClosed {
* println("Can not send: the channel is closed")
* }
* ```
*
* The primary intended usage of this property is skipping some portions of code that should not be executed if the
* channel is already known to be closed.
* For example:
*
* ```
* if (channel.isClosedForSend) {
* // fast path
* return
* } else {
* // slow path: actually computing the value
* val nextElement = run {
* // some heavy computation
* }
* channel.send(nextElement) // can fail anyway,
* // but at least we tried to avoid the computation
* }
* ```
*
* However, in many cases, even that can be achieved more idiomatically by cancelling the coroutine producing the
* elements to send.
* See [produce] for a way to launch a coroutine that produces elements and cancels itself when the channel is
* closed.
*
* [isClosedForSend] can also be used for assertions and diagnostics to verify the expected state of the channel.
*
* @see SendChannel.trySend
* @see SendChannel.close
* @see ReceiveChannel.cancel
*/
@DelicateCoroutinesApi
public val isClosedForSend: Boolean
/**
* Sends the specified [element] to this channel.
*
* This function suspends if it does not manage to pass the element to the channel's buffer
* (or directly the receiving side if there's no buffer),
* and it can be cancelled with or without having successfully passed the element.
* See the "Suspending and cancellation" section below for details.
* If the channel is [closed][close], an exception is thrown (see below).
*
* ```
* val channel = Channel<Int>()
* launch {
* check(channel.receive() == 5)
* }
* channel.send(5) // suspends until 5 is received
* ```
*
* ## Suspending and cancellation
*
* If the [BufferOverflow] strategy of this channel is [BufferOverflow.SUSPEND],
* this function may suspend.
* The exact scenarios differ depending on the channel's capacity:
* - If the channel is [rendezvous][RENDEZVOUS],
* the sender will be suspended until the receiver calls [ReceiveChannel.receive].
* - If the channel is [unlimited][UNLIMITED] or [conflated][CONFLATED],
* the sender will never be suspended even with the [BufferOverflow.SUSPEND] strategy.
* - If the channel is buffered (either [BUFFERED] or uses a non-default buffer capacity),
* the sender will be suspended until the buffer has free space.
*
* This suspending function is cancellable: if the [Job] of the current coroutine is cancelled while this
* suspending function is waiting, this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**: even if [send] managed to send the element, but was cancelled
* while suspended, [CancellationException] will be thrown. See [suspendCancellableCoroutine] for low-level details.
*
* Because of the prompt cancellation guarantee, an exception does not always mean a failure to deliver the element.
* See the "Undelivered elements" section in the [Channel] documentation
* for details on handling undelivered elements.
*
* Note that this function does not check for cancellation when it is not suspended.
* Use [ensureActive] or [CoroutineScope.isActive] to periodically check for cancellation in tight loops if needed:
*
* ```
* // because of UNLIMITED, sending to this channel never suspends
* val channel = Channel<Int>(Channel.UNLIMITED)
* val job = launch {
* while (isActive) {
* channel.send(42)
* }
* // the loop exits when the job is cancelled
* }
* ```
*
* This isn't needed if other cancellable functions are called inside the loop, like [delay].
*
* ## Sending to a closed channel
*
* If a channel was [closed][close] before [send] was called and no cause was specified,
* an [ClosedSendChannelException] will be thrown from [send].
* If a channel was [closed][close] with a cause before [send] was called,
* then [send] will rethrow the same (in the `===` sense) exception that was passed to [close].
*
* In both cases, it is guaranteed that the element was not delivered to the consumer,
* and the `onUndeliveredElement` callback will be called.
* See the "Undelivered elements" section in the [Channel] documentation
* for details on handling undelivered elements.
*
* [Closing][close] a channel _after_ this function suspends does not cause this suspended [send] invocation
* to abort: although subsequent invocations of [send] fail, the existing ones will continue to completion,
* unless the sending coroutine is cancelled.
*
* ## Related
*
* This function can be used in [select] invocations with the [onSend] clause.
* Use [trySend] to try sending to this channel without waiting and throwing.
*/
public suspend fun send(element: E)
/**
* Clause for the [select] expression of the [send] suspending function that selects when the element that is
* specified as the parameter is sent to the channel.
* When the clause is selected, the reference to this channel is passed into the corresponding block.
*
* The [select] invocation fails with an exception if the channel [is closed for `send`][isClosedForSend] before
* the [select] suspends (see the "Sending to a closed channel" section of [send]).
*
* Example:
* ```
* val sendChannels = List(4) { index ->
* Channel<Int>(onUndeliveredElement = {
* println("Undelivered element $it for $index")
* }).also { channel ->
* // launch a consumer for this channel
* launch {
* withTimeout(1.seconds) {
* println("Consumer $index receives: ${channel.receive()}")
* }
* }
* }
* }
* val element = 42
* select {
* for (channel in sendChannels) {
* channel.onSend(element) {
* println("Sent to channel $it")
* }
* }
* }
* ```
* Here, we start a [select] expression that waits for exactly one of the four [onSend] invocations
* to successfully send the element to the receiver,
* and the other three will instead invoke the `onUndeliveredElement` callback.
* See the "Undelivered elements" section in the [Channel] documentation
* for details on handling undelivered elements.
*
* Like [send], [onSend] obeys the rules of prompt cancellation:
* [select] may finish with a [CancellationException] even if the element was successfully sent.
*/
public val onSend: SelectClause2<E, SendChannel<E>>
/**
* Attempts to add the specified [element] to this channel without waiting.
*
* [trySend] never suspends and never throws exceptions.
* Instead, it returns a [ChannelResult] that encapsulates the result of the operation.
* This makes it different from [send], which can suspend and throw exceptions.
*
* If this channel is currently full and cannot receive new elements at the time or is [closed][close],
* this function returns a result that indicates [a failure][ChannelResult.isFailure].
* In this case, it is guaranteed that the element was not delivered to the consumer and the
* `onUndeliveredElement` callback, if one is provided during the [Channel]'s construction, does *not* get called.
*
* [trySend] can be used as a non-`suspend` alternative to [send] in cases where it's known beforehand
* that the channel's buffer can not overflow.
* ```
* class Coordinates(val x: Int, val y: Int)
* // A channel for a single subscriber that stores the latest mouse position update.
* // If more than one subscriber is expected, consider using a `StateFlow` instead.
* val mousePositionUpdates = Channel<Coordinates>(Channel.CONFLATED)
* // Notifies the subscriber about the new mouse position.
* // If the subscriber is slow, the intermediate updates are dropped.
* fun moveMouse(coordinates: Coordinates) {
* val result = mousePositionUpdates.trySend(coordinates)
* if (result.isClosed) {
* error("Mouse position is no longer being processed")
* }
* }
* ```
*/
public fun trySend(element: E): ChannelResult<Unit>
/**
* Closes this channel so that subsequent attempts to [send] to it fail.
*
* Returns `true` if the channel was not closed previously and the call to this function closed it.
* If the channel was already closed, this function does nothing and returns `false`.
*
* The existing elements in the channel remain there, and likewise,
* the calls to [send] an [onSend] that have suspended before [close] was called will not be affected.
* Only the subsequent calls to [send], [trySend], or [onSend] will fail.
* [isClosedForSend] will start returning `true` immediately after this function is called.
*
* Once all the existing elements are received, the channel will be considered closed for `receive` as well.
* This means that [receive][ReceiveChannel.receive] will also start throwing exceptions.
* At that point, [isClosedForReceive][ReceiveChannel.isClosedForReceive] will start returning `true`.
*
* If the [cause] is non-null, it will be thrown from all the subsequent attempts to [send] to this channel,
* as well as from all the attempts to [receive][ReceiveChannel.receive] from the channel after no elements remain.
*
* If the [cause] is null, the channel is considered to have completed normally.
* All subsequent calls to [send] will throw a [ClosedSendChannelException],
* whereas calling [receive][ReceiveChannel.receive] will throw a [ClosedReceiveChannelException]
* after there are no more elements.
*
* ```
* val channel = Channel<Int>()
* channel.send(1)
* channel.close()
* try {
* channel.send(2)
* error("The channel is closed, so this line is never reached")
* } catch (e: ClosedSendChannelException) {
* // expected
* }
* ```
*/
public fun close(cause: Throwable? = null): Boolean
/**
* Registers a [handler] that is synchronously invoked once the channel is [closed][close]
* or the receiving side of this channel is [cancelled][ReceiveChannel.cancel].
* Only one handler can be attached to a channel during its lifetime.
* The `handler` is invoked when [isClosedForSend] starts to return `true`.
* If the channel is closed already, the handler is invoked immediately.
*
* The meaning of `cause` that is passed to the handler:
* - `null` if the channel was [closed][close] normally with `cause = null`.
* - Instance of [CancellationException] if the channel was [cancelled][ReceiveChannel.cancel] normally
* without the corresponding argument.
* - The cause of `close` or `cancel` otherwise.
*
* ### Execution context and exception safety
*
* The [handler] is executed as part of the closing or cancelling operation,
* and only after the channel reaches its final state.
* This means that if the handler throws an exception or hangs,
* the channel will still be successfully closed or cancelled.
* Unhandled exceptions from [handler] are propagated to the closing or cancelling operation's caller.
*
* Example of usage:
* ```
* val events = Channel<Event>(Channel.UNLIMITED)
* callbackBasedApi.registerCallback { event ->
* events.trySend(event)
* .onClosed { /* channel is already closed, but the callback hasn't stopped yet */ }
* }
*
* val uiUpdater = uiScope.launch(Dispatchers.Main) {
* events.consume { /* handle events */ }
* }
* // Stop the callback after the channel is closed or cancelled
* events.invokeOnClose { callbackBasedApi.stop() }
* ```
*
* **Stability note.** This function constitutes a stable API surface, with the only exception being
* that an [IllegalStateException] is thrown when multiple handlers are registered.
* This restriction could be lifted in the future.
*
* @throws UnsupportedOperationException if the underlying channel does not support [invokeOnClose].
* Implementation note: currently, [invokeOnClose] is unsupported only by Rx-like integrations.
*
* @throws IllegalStateException if another handler was already registered
*/
public fun invokeOnClose(handler: (cause: Throwable?) -> Unit)
/**
* **Deprecated** offer method.
*
* This method was deprecated in the favour of [trySend].
* It has proven itself as the most error-prone method in Channel API:
*
* - `Boolean` return type creates the false sense of security, implying that `false`
* is returned instead of throwing an exception.
* - It was used mostly from non-suspending APIs where CancellationException triggered
* internal failures in the application (the most common source of bugs).
* - Due to signature and explicit `if (ch.offer(...))` checks it was easy to
* oversee such error during code review.
* - Its name was not aligned with the rest of the API and tried to mimic Java's queue instead.
*
* **NB** Automatic migration provides best-effort for the user experience, but requires removal
* or adjusting of the code that relied on the exception handling.
* The complete replacement has a more verbose form:
* ```
* channel.trySend(element)
* .onClosed { throw it ?: ClosedSendChannelException("Channel was closed normally") }
* .isSuccess
* ```
*
* See https://github.com/Kotlin/kotlinx.coroutines/issues/974 for more context.
*
* @suppress **Deprecated**.
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Deprecated in the favour of 'trySend' method",
replaceWith = ReplaceWith("trySend(element).isSuccess")
) // Warning since 1.5.0, error since 1.6.0, not hidden until 1.8+ because API is quite widespread
public fun offer(element: E): Boolean {
val result = trySend(element)
if (result.isSuccess) return true
throw recoverStackTrace(result.exceptionOrNull() ?: return false)
}
}
/**
* Receiver's interface to a [Channel].
*
* Combined, [SendChannel] and [ReceiveChannel] define the complete [Channel] interface.
*/
public interface ReceiveChannel<out E> {
/**
* Returns `true` if the sending side of this channel was [closed][SendChannel.close]
* and all previously sent items were already received (which also happens for [cancelled][cancel] channels).
*
* Note that if this property returns `false`,
* it does not guarantee that a subsequent call to [receive] will succeed,
* as the channel can be concurrently cancelled or closed right after the check.
* For such scenarios, [receiveCatching] is the more robust solution:
* if the channel is closed, instead of throwing an exception, [receiveCatching] returns a result that allows
* querying it.
*
* ```
* // DANGER! THIS CHECK IS NOT RELIABLE!
* if (!channel.isClosedForReceive) {
* channel.receive() // can still fail!
* } else {
* println("Can not receive: the channel is closed")
* null
* }
* // DO THIS INSTEAD:
* channel.receiveCatching().onClosed {
* println("Can not receive: the channel is closed")
* }.getOrNull()
* ```
*
* The primary intended usage of this property is for assertions and diagnostics to verify the expected state of
* the channel.
* Using it in production code is discouraged.
*
* @see ReceiveChannel.receiveCatching
* @see ReceiveChannel.cancel
* @see SendChannel.close
*/
@DelicateCoroutinesApi
public val isClosedForReceive: Boolean
/**
* Returns `true` if the channel contains no elements and isn't [closed for `receive`][isClosedForReceive].
*
* If [isEmpty] returns `true`, it means that calling [receive] at exactly the same moment would suspend.
* However, calling [receive] immediately after checking [isEmpty] may or may not suspend, as new elements
* could have been added or removed or the channel could have been closed for `receive` between the two invocations.
* Consider using [tryReceive] in cases when suspensions are undesirable:
*
* ```
* // DANGER! THIS CHECK IS NOT RELIABLE!
* while (!channel.isEmpty) {
* // can still suspend if other `receive` happens in parallel!
* val element = channel.receive()
* println(element)
* }
* // DO THIS INSTEAD:
* while (true) {
* val element = channel.tryReceive().getOrNull() ?: break
* println(element)
* }
* ```
*/
@ExperimentalCoroutinesApi
public val isEmpty: Boolean
/**
* Retrieves an element, removing it from the channel.
*
* This function suspends if the channel is empty, waiting until an element is available.
* If the channel is [closed for `receive`][isClosedForReceive], an exception is thrown (see below).
* ```
* val channel = Channel<Int>()
* launch {
* val element = channel.receive() // suspends until 5 is available
* check(element == 5)
* }
* channel.send(5)
* ```
*
* ## Suspending and cancellation
*
* This suspending function is cancellable: if the [Job] of the current coroutine is cancelled while this
* suspending function is waiting, this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**: even if [receive] managed to retrieve the element from the channel,
* but was cancelled while suspended, [CancellationException] will be thrown, and, if
* the channel has an `onUndeliveredElement` callback installed, the retrieved element will be passed to it.
* See the "Undelivered elements" section in the [Channel] documentation
* for details on handling undelivered elements.
* See [suspendCancellableCoroutine] for the low-level details of prompt cancellation.
*
* Note that this function does not check for cancellation when it manages to immediately receive an element without
* suspending.
* Use [ensureActive] or [CoroutineScope.isActive] to periodically check for cancellation in tight loops if needed:
*
* ```
* val channel = Channel<Int>()
* launch { // a very fast producer
* while (true) {
* channel.send(42)
* }
* }
* val consumer = launch { // a slow consumer
* while (isActive) {
* val element = channel.receive()
* // some slow computation involving `element`
* }
* }
* delay(100.milliseconds)
* consumer.cancelAndJoin()
* ```
*
* ## Receiving from a closed channel
*
* - Attempting to [receive] from a [closed][SendChannel.close] channel while there are still some elements
* will successfully retrieve an element from the channel.
* - When a channel is [closed][SendChannel.close] and there are no elements remaining,
* the channel becomes [closed for `receive`][isClosedForReceive].
* After that,
* [receive] will rethrow the same (in the `===` sense) exception that was passed to [SendChannel.close],
* or [ClosedReceiveChannelException] if none was given.
*
* ## Related
*
* This function can be used in [select] invocations with the [onReceive] clause.
* Use [tryReceive] to try receiving from this channel without waiting and throwing.
* Use [receiveCatching] to receive from this channel without throwing.
*/
public suspend fun receive(): E
/**
* Clause for the [select] expression of the [receive] suspending function that selects with the element
* received from the channel.
*
* The [select] invocation fails with an exception if the channel [is closed for `receive`][isClosedForReceive]
* at any point, even if other [select] clauses could still work.
*
* Example:
* ```
* class ScreenSize(val width: Int, val height: Int)
* class MouseClick(val x: Int, val y: Int)
* val screenResizes = Channel<ScreenSize>(Channel.CONFLATED)
* val mouseClicks = Channel<MouseClick>(Channel.CONFLATED)
*
* launch(Dispatchers.Main) {
* while (true) {
* select {
* screenResizes.onReceive { newSize ->
* // update the UI to the new screen size
* }
* mouseClicks.onReceive { click ->
* // react to a mouse click
* }
* }
* }
* }
* ```
*
* Like [receive], [onReceive] obeys the rules of prompt cancellation:
* [select] may finish with a [CancellationException] even if an element was successfully retrieved,
* in which case the `onUndeliveredElement` callback will be called.
*/
public val onReceive: SelectClause1<E>
/**
* Retrieves an element, removing it from the channel.
*
* A difference from [receive] is that this function encapsulates a failure in its return value instead of throwing
* an exception.
* However, it will still throw [CancellationException] if the coroutine calling [receiveCatching] is cancelled.
*
* It is guaranteed that the only way this function can return a [failed][ChannelResult.isFailure] result is when
* the channel is [closed for `receive`][isClosedForReceive], so [ChannelResult.isClosed] is also true.
*
* This function suspends if the channel is empty, waiting until an element is available or the channel becomes
* closed.
* ```
* val channel = Channel<Int>()
* launch {
* while (true) {
* val result = channel.receiveCatching() // suspends
* when (val element = result.getOrNull()) {
* null -> break // the channel is closed
* else -> check(element == 5)
* }
* }
* }
* channel.send(5)
* ```
*
* ## Suspending and cancellation
*
* This suspending function is cancellable: if the [Job] of the current coroutine is cancelled while this
* suspending function is waiting, this function immediately resumes with [CancellationException].
* There is a **prompt cancellation guarantee**: even if [receiveCatching] managed to retrieve the element from the
* channel, but was cancelled while suspended, [CancellationException] will be thrown, and, if
* the channel has an `onUndeliveredElement` callback installed, the retrieved element will be passed to it.
* See the "Undelivered elements" section in the [Channel] documentation
* for details on handling undelivered elements.
* See [suspendCancellableCoroutine] for the low-level details of prompt cancellation.
*
* Note that this function does not check for cancellation when it manages to immediately receive an element without
* suspending.
* Use [ensureActive] or [CoroutineScope.isActive] to periodically check for cancellation in tight loops if needed:
*
* ```
* val channel = Channel<Int>()
* launch { // a very fast producer
* while (true) {
* channel.send(42)
* }
* }
* val consumer = launch { // a slow consumer
* while (isActive) {
* val element = channel.receiveCatching().getOrNull() ?: break
* // some slow computation involving `element`
* }
* }
* delay(100.milliseconds)
* consumer.cancelAndJoin()
* ```
*
* ## Receiving from a closed channel
*
* - Attempting to [receiveCatching] from a [closed][SendChannel.close] channel while there are still some elements
* will successfully retrieve an element from the channel.
* - When a channel is [closed][SendChannel.close] and there are no elements remaining,
* the channel becomes [closed for `receive`][isClosedForReceive].
* After that, [receiveCatching] will return a result with [ChannelResult.isClosed] set.
* [ChannelResult.exceptionOrNull] will be the exact (in the `===` sense) exception
* that was passed to [SendChannel.close],
* or `null` if none was given.
*
* ## Related
*
* This function can be used in [select] invocations with the [onReceiveCatching] clause.
* Use [tryReceive] to try receiving from this channel without waiting and throwing.
* Use [receive] to receive from this channel and throw exceptions on error.
*/
public suspend fun receiveCatching(): ChannelResult<E>
/**
* Clause for the [select] expression of the [receiveCatching] suspending function that selects
* with a [ChannelResult] when an element is retrieved or the channel gets closed.
*
* Like [receiveCatching], [onReceiveCatching] obeys the rules of prompt cancellation:
* [select] may finish with a [CancellationException] even if an element was successfully retrieved,
* in which case the `onUndeliveredElement` callback will be called.
*/
// TODO: think of an example of when this could be useful
public val onReceiveCatching: SelectClause1<ChannelResult<E>>
/**
* Attempts to retrieve an element without waiting, removing it from the channel.
*
* - When the channel is non-empty, a [successful][ChannelResult.isSuccess] result is returned,
* and [ChannelResult.getOrNull] returns the retrieved element.
* - When the channel is empty, a [failed][ChannelResult.isFailure] result is returned.
* - When the channel is already [closed for `receive`][isClosedForReceive],
* returns the ["channel is closed"][ChannelResult.isClosed] result.
* If the channel was [closed][SendChannel.close] with a cause (for example, [cancelled][cancel]),
* [ChannelResult.exceptionOrNull] contains the cause.
*
* This function is useful when implementing on-demand allocation of resources to be stored in the channel:
*
* ```
* val resourcePool = Channel<Resource>(maxResources)
*
* suspend fun withResource(block: (Resource) -> Unit) {
* val result = resourcePool.tryReceive()
* val resource = result.getOrNull()
* ?: tryCreateNewResource() // try to create a new resource
* ?: resourcePool.receive() // could not create: actually wait for the resource
* try {
* block(resource)
* } finally {
* resourcePool.trySend(resource)
* }
* }
* ```
*/
public fun tryReceive(): ChannelResult<E>
/**
* Returns a new iterator to receive elements from this channel using a `for` loop.
* Iteration completes normally when the channel [is closed for `receive`][isClosedForReceive] without a cause and
* throws the exception passed to [close][SendChannel.close] if there was one.
*
* Instances of [ChannelIterator] are not thread-safe and shall not be used from concurrent coroutines.
*
* Example:
*
* ```
* val channel = produce<Int> {
* repeat(1000) {
* send(it)
* }
* }
* for (v in channel) {
* println(v)
* }
* ```
*
* Note that if an early return happens from the `for` loop, the channel does not get cancelled.
* To forbid sending new elements after the iteration is completed, use [consumeEach] or
* call [cancel] manually.
*/
public operator fun iterator(): ChannelIterator<E>
/**
* [Closes][SendChannel.close] the channel for new elements and removes all existing ones.
*
* A [cause] can be used to specify an error message or to provide other details on
* the cancellation reason for debugging purposes.
* If the cause is not specified, then an instance of [CancellationException] with a
* default message is created to [close][SendChannel.close] the channel.
*
* If the channel was already [closed][SendChannel.close],
* [cancel] only has the effect of removing all elements from the channel.
*
* Immediately after the invocation of this function,
* [isClosedForReceive] and, on the [SendChannel] side, [isClosedForSend][SendChannel.isClosedForSend]
* start returning `true`.
* Any attempt to send to or receive from this channel will lead to a [CancellationException].
* This also applies to the existing senders and receivers that are suspended at the time of the call:
* they will be resumed with a [CancellationException] immediately after [cancel] is called.
*
* If the channel has an `onUndeliveredElement` callback installed, this function will invoke it for each of the
* elements still in the channel, since these elements will be inaccessible otherwise.
* If the callback is not installed, these elements will simply be removed from the channel for garbage collection.
*
* ```
* val channel = Channel<Int>()
* channel.send(1)
* channel.send(2)
* channel.cancel()
* channel.trySend(3) // returns ChannelResult.isClosed
* for (element in channel) { println(element) } // prints nothing
* ```
*
* [consume] and [consumeEach] are convenient shorthands for cancelling the channel after the single consumer
* has finished processing.
*/
public fun cancel(cause: CancellationException? = null)
/**
* @suppress This method implements old version of JVM ABI. Use [cancel].
*/
@Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
public fun cancel(): Unit = cancel(null)
/**
* @suppress This method has bad semantics when cause is not a [CancellationException]. Use [cancel].
*/
@Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
public fun cancel(cause: Throwable? = null): Boolean
/**
* **Deprecated** poll method.
*
* This method was deprecated in the favour of [tryReceive].
* It has proven itself as error-prone method in Channel API:
*
* - Nullable return type creates the false sense of security, implying that `null`
* is returned instead of throwing an exception.
* - It was used mostly from non-suspending APIs where CancellationException triggered
* internal failures in the application (the most common source of bugs).
* - Its name was not aligned with the rest of the API and tried to mimic Java's queue instead.
*
* See https://github.com/Kotlin/kotlinx.coroutines/issues/974 for more context.
*
* ### Replacement note
*
* The replacement `tryReceive().getOrNull()` is a default that ignores all close exceptions and
* proceeds with `null`, while `poll` throws an exception if the channel was closed with an exception.
* Replacement with the very same 'poll' semantics is `tryReceive().onClosed { if (it != null) throw it }.getOrNull()`
*
* @suppress **Deprecated**.
*/
@Deprecated(
level = DeprecationLevel.ERROR,
message = "Deprecated in the favour of 'tryReceive'. " +
"Please note that the provided replacement does not rethrow channel's close cause as 'poll' did, " +
"for the precise replacement please refer to the 'poll' documentation",
replaceWith = ReplaceWith("tryReceive().getOrNull()")
) // Warning since 1.5.0, error since 1.6.0, not hidden until 1.8+ because API is quite widespread
public fun poll(): E? {
val result = tryReceive()
if (result.isSuccess) return result.getOrThrow()
throw recoverStackTrace(result.exceptionOrNull() ?: return null)
}
/**
* This function was deprecated since 1.3.0 and is no longer recommended to use
* or to implement in subclasses.
*
* It had the following pitfalls:
* - Didn't allow to distinguish 'null' as "closed channel" from "null as a value"
* - Was throwing if the channel has failed even though its signature may suggest it returns 'null'
* - It didn't really belong to core channel API and can be exposed as an extension instead.
*
* ### Replacement note
*
* The replacement `receiveCatching().getOrNull()` is a safe default that ignores all close exceptions and
* proceeds with `null`, while `receiveOrNull` throws an exception if the channel was closed with an exception.
* Replacement with the very same `receiveOrNull` semantics is `receiveCatching().onClosed { if (it != null) throw it }.getOrNull()`.
*
* @suppress **Deprecated**
*/
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
@LowPriorityInOverloadResolution
@Deprecated(
message = "Deprecated in favor of 'receiveCatching'. " +
"Please note that the provided replacement does not rethrow channel's close cause as 'receiveOrNull' did, " +
"for the detailed replacement please refer to the 'receiveOrNull' documentation",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("receiveCatching().getOrNull()")
) // Warning since 1.3.0, error in 1.5.0, cannot be hidden due to deprecated extensions
public suspend fun receiveOrNull(): E? = receiveCatching().getOrNull()
/**
* This function was deprecated since 1.3.0 and is no longer recommended to use
* or to implement in subclasses.
* See [receiveOrNull] documentation.
*
* @suppress **Deprecated**: in favor of onReceiveCatching extension.
*/
@Suppress("DEPRECATION_ERROR")
@Deprecated(
message = "Deprecated in favor of onReceiveCatching extension",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("onReceiveCatching")
) // Warning since 1.3.0, error in 1.5.0, will be hidden or removed in 1.7.0
public val onReceiveOrNull: SelectClause1<E?> get() = (this as BufferedChannel<E>).onReceiveOrNull
}
/**
* A discriminated union representing a channel operation result.
* It encapsulates the knowledge of whether the operation succeeded, failed with an option to retry,
* or failed because the channel was closed.
*
* If the operation was [successful][isSuccess], [T] is the result of the operation:
* for example, for [ReceiveChannel.receiveCatching] and [ReceiveChannel.tryReceive],
* it is the element received from the channel, and for [Channel.trySend], it is [Unit],
* as the channel does not receive anything in return for sending a channel.
* This value can be retrieved with [getOrNull] or [getOrThrow].
*
* If the operation [failed][isFailure], it does not necessarily mean that the channel itself is closed.
* For example, [ReceiveChannel.receiveCatching] and [ReceiveChannel.tryReceive] can fail because the channel is empty,
* and [Channel.trySend] can fail because the channel is full.
*
* If the operation [failed][isFailure] because the channel was closed for that operation, [isClosed] returns `true`.
* The opposite is also true: if [isClosed] returns `true`, then the channel is closed for that operation
* ([ReceiveChannel.isClosedForReceive] or [SendChannel.isClosedForSend]).
* In this case, retrying the operation is meaningless: once closed, the channel will remain closed.
* The [exceptionOrNull] function returns the reason the channel was closed, if any was given.
*
* Manually obtaining a [ChannelResult] instance is not supported.
* See the documentation for [ChannelResult]-returning functions for usage examples.
*/
@JvmInline
public value class ChannelResult<out T>
@PublishedApi internal constructor(@PublishedApi internal val holder: Any?) {
/**
* Whether the operation succeeded.
*
* If this returns `true`, the operation was successful.
* In this case, [getOrNull] and [getOrThrow] can be used to retrieve the value.
*
* If this returns `false`, the operation failed.
* [isClosed] can be used to determine whether the operation failed because the channel was closed
* (and therefore retrying the operation is meaningless).
*
* ```
* val result = channel.tryReceive()
* if (result.isSuccess) {
* println("Successfully received the value ${result.getOrThrow()}")
* } else {
* println("Failed to receive the value.")
* if (result.isClosed) {
* println("The channel is closed.")
* if (result.exceptionOrNull() != null) {
* println("The reason: ${result.exceptionOrNull()}")
* }
* }
* }
* ```
*
* [isFailure] is a shorthand for `!isSuccess`.
* [getOrNull] can simplify [isSuccess] followed by [getOrThrow] into just one check if [T] is known
* to be non-nullable.
*/
public val isSuccess: Boolean get() = holder !is Failed
/**
* Whether the operation failed.
*
* A shorthand for `!isSuccess`. See [isSuccess] for more details.
*/
public val isFailure: Boolean get() = holder is Failed
/**
* Whether the operation failed because the channel was closed.
*
* If this returns `true`, the channel was closed for the operation that returned this result.
* In this case, retrying the operation is meaningless: once closed, the channel will remain closed.
* [isSuccess] will return `false`.
* [exceptionOrNull] can be used to determine the reason the channel was [closed][SendChannel.close]
* if one was given.
*
* If this returns `false`, subsequent attempts to perform the same operation may succeed.
*
* ```
* val result = channel.trySend(42)
* if (result.isClosed) {
* println("The channel is closed.")
* if (result.exceptionOrNull() != null) {
* println("The reason: ${result.exceptionOrNull()}")
* }
* }
*/
public val isClosed: Boolean get() = holder is Closed
/**
* Returns the encapsulated [T] if the operation succeeded, or `null` if it failed.
*
* For non-nullable [T], the following code can be used to handle the result:
* ```
* val result = channel.tryReceive()
* val value = result.getOrNull()
* if (value == null) {
* if (result.isClosed) {
* println("The channel is closed.")
* if (result.exceptionOrNull() != null) {
* println("The reason: ${result.exceptionOrNull()}")
* }
* }
* return
* }
* println("Successfully received the value $value")
* ```
*
* If [T] is nullable, [getOrThrow] together with [isSuccess] is a more reliable way to handle the result.
*/
@Suppress("UNCHECKED_CAST")
public fun getOrNull(): T? = if (holder !is Failed) holder as T else null
/**
* Returns the encapsulated [T] if the operation succeeded, or throws the encapsulated exception if it failed.
*
* Example:
* ```
* val result = channel.tryReceive()
* if (result.isSuccess) {
* println("Successfully received the value ${result.getOrThrow()}")
* }
* ```
*
* @throws IllegalStateException if the operation failed, but the channel was not closed with a cause.
*/
public fun getOrThrow(): T {
@Suppress("UNCHECKED_CAST")
if (holder !is Failed) return holder as T
if (holder is Closed) {
check(holder.cause != null) { "Trying to call 'getOrThrow' on a channel closed without a cause" }
throw holder.cause
}
error("Trying to call 'getOrThrow' on a failed result of a non-closed channel")
}
/**
* Returns the exception with which the channel was closed, or `null` if the channel was not closed or was closed
* without a cause.
*
* [exceptionOrNull] can only return a non-`null` value if [isClosed] is `true`,
* but even if [isClosed] is `true`,
* [exceptionOrNull] can still return `null` if the channel was closed without a cause.
*
* ```
* val result = channel.tryReceive()
* if (result.isClosed) {
* // Now we know not to retry the operation later.
* // Check if the channel was closed with a cause and rethrow the exception:
* result.exceptionOrNull()?.let { throw it }
* // Otherwise, the channel was closed without a cause.
* }
* ```
*/
public fun exceptionOrNull(): Throwable? = (holder as? Closed)?.cause
internal open class Failed {
override fun toString(): String = "Failed"
}
internal class Closed(@JvmField val cause: Throwable?): Failed() {
override fun equals(other: Any?): Boolean = other is Closed && cause == other.cause
override fun hashCode(): Int = cause.hashCode()
override fun toString(): String = "Closed($cause)"
}
/**
* @suppress **This is internal API and it is subject to change.**
*/
@InternalCoroutinesApi
public companion object {
private val failed = Failed()
@InternalCoroutinesApi
public fun <E> success(value: E): ChannelResult<E> =
ChannelResult(value)
@InternalCoroutinesApi
public fun <E> failure(): ChannelResult<E> =
ChannelResult(failed)
@InternalCoroutinesApi
public fun <E> closed(cause: Throwable?): ChannelResult<E> =
ChannelResult(Closed(cause))
}
public override fun toString(): String =
when (holder) {
is Closed -> holder.toString()
else -> "Value($holder)"
}
}
/**
* Returns the encapsulated value if the operation [succeeded][ChannelResult.isSuccess], or the
* result of [onFailure] function for [ChannelResult.exceptionOrNull] otherwise.
*
* A shorthand for `if (isSuccess) getOrNull() else onFailure(exceptionOrNull())`.
*
* @see ChannelResult.getOrNull
* @see ChannelResult.exceptionOrNull
*/
@OptIn(ExperimentalContracts::class)
public inline fun <T> ChannelResult<T>.getOrElse(onFailure: (exception: Throwable?) -> T): T {
contract {
callsInPlace(onFailure, InvocationKind.AT_MOST_ONCE)
}
@Suppress("UNCHECKED_CAST")
return if (holder is ChannelResult.Failed) onFailure(exceptionOrNull()) else holder as T
}
/**
* Performs the given [action] on the encapsulated value if the operation [succeeded][ChannelResult.isSuccess].