@@ -58,12 +58,51 @@ public interface Delay {
58
58
DefaultDelay .invokeOnTimeout(timeMillis, block)
59
59
}
60
60
61
+ /* *
62
+ * Suspends until cancellation, in which case it will throw a [CancellationException].
63
+ *
64
+ * This function returns [Nothing], so it can be used in any coroutine,
65
+ * regardless of the required return type.
66
+ *
67
+ * Usage example in callback adapting code:
68
+ *
69
+ * ```kotlin
70
+ * fun currentTemperature(): Flow<Temperature> = callbackFlow {
71
+ * val callback = SensorCallback { degreesCelsius: Double ->
72
+ * trySend(Temperature.celsius(degreesCelsius))
73
+ * }
74
+ * try {
75
+ * registerSensorCallback(callback)
76
+ * awaitCancellation() // Suspends to keep getting updates until cancellation.
77
+ * } finally {
78
+ * unregisterSensorCallback(callback)
79
+ * }
80
+ * }
81
+ * ```
82
+ *
83
+ * Usage example in (non declarative) UI code:
84
+ *
85
+ * ```kotlin
86
+ * suspend fun showStuffUntilCancelled(content: Stuff): Nothing {
87
+ * someSubView.text = content.title
88
+ * anotherSubView.text = content.description
89
+ * someView.visibleInScope {
90
+ * awaitCancellation() // Suspends so the view stays visible.
91
+ * }
92
+ * }
93
+ * ```
94
+ */
95
+ @ExperimentalCoroutinesApi
96
+ public suspend fun awaitCancellation (): Nothing = suspendCancellableCoroutine {}
97
+
61
98
/* *
62
99
* Delays coroutine for a given time without blocking a thread and resumes it after a specified time.
63
100
* This suspending function is cancellable.
64
101
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
65
102
* immediately resumes with [CancellationException].
66
103
*
104
+ * If you want to delay forever (until cancellation), consider using [awaitCancellation] instead.
105
+ *
67
106
* Note that delay can be used in [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
68
107
*
69
108
* Implementation note: how exactly time is tracked is an implementation detail of [CoroutineDispatcher] in the context.
@@ -82,6 +121,8 @@ public suspend fun delay(timeMillis: Long) {
82
121
* If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
83
122
* immediately resumes with [CancellationException].
84
123
*
124
+ * If you want to delay forever (until cancellation), consider using [awaitCancellation] instead.
125
+ *
85
126
* Note that delay can be used in [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
86
127
*
87
128
* Implementation note: how exactly time is tracked is an implementation detail of [CoroutineDispatcher] in the context.
0 commit comments