@@ -10,6 +10,8 @@ import kotlinx.coroutines.selects.*
10
10
import kotlin.coroutines.*
11
11
import kotlin.coroutines.intrinsics.*
12
12
import kotlin.jvm.*
13
+ import kotlin.time.Duration
14
+ import kotlin.time.ExperimentalTime
13
15
14
16
/* *
15
17
* Runs a given suspending [block] of code inside a coroutine with a specified [timeout][timeMillis] and throws
@@ -32,6 +34,22 @@ public suspend fun <T> withTimeout(timeMillis: Long, block: suspend CoroutineSco
32
34
}
33
35
}
34
36
37
+ /* *
38
+ * Runs a given suspending [block] of code inside a coroutine with the specified [timeout] and throws
39
+ * a [TimeoutCancellationException] if the timeout was exceeded.
40
+ *
41
+ * The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of
42
+ * the cancellable suspending function inside the block throws a [TimeoutCancellationException].
43
+ *
44
+ * The sibling function that does not throw an exception on timeout is [withTimeoutOrNull].
45
+ * Note that the timeout action can be specified for a [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
46
+ *
47
+ * Implementation note: how the time is tracked exactly is an implementation detail of the context's [CoroutineDispatcher].
48
+ */
49
+ @ExperimentalTime
50
+ public suspend fun <T > withTimeout (timeout : Duration , block : suspend CoroutineScope .() -> T ): T =
51
+ withTimeout(timeout.toDelayMillis(), block)
52
+
35
53
/* *
36
54
* Runs a given suspending block of code inside a coroutine with a specified [timeout][timeMillis] and returns
37
55
* `null` if this timeout was exceeded.
@@ -65,6 +83,22 @@ public suspend fun <T> withTimeoutOrNull(timeMillis: Long, block: suspend Corout
65
83
}
66
84
}
67
85
86
+ /* *
87
+ * Runs a given suspending block of code inside a coroutine with the specified [timeout] and returns
88
+ * `null` if this timeout was exceeded.
89
+ *
90
+ * The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of
91
+ * cancellable suspending function inside the block throws a [TimeoutCancellationException].
92
+ *
93
+ * The sibling function that throws an exception on timeout is [withTimeout].
94
+ * Note that the timeout action can be specified for a [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
95
+ *
96
+ * Implementation note: how the time is tracked exactly is an implementation detail of the context's [CoroutineDispatcher].
97
+ */
98
+ @ExperimentalTime
99
+ public suspend fun <T > withTimeoutOrNull (timeout : Duration , block : suspend CoroutineScope .() -> T ): T ? =
100
+ withTimeoutOrNull(timeout.toDelayMillis(), block)
101
+
68
102
private fun <U , T : U > setupTimeout (
69
103
coroutine : TimeoutCoroutine <U , T >,
70
104
block : suspend CoroutineScope .() -> T
0 commit comments