Skip to content

Commit b55c1c9

Browse files
authored
Stabilize CoroutineStart.ATOMIC (#4169)
1 parent 2d9f944 commit b55c1c9

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

kotlinx-coroutines-core/common/src/CoroutineStart.kt

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,30 @@ public enum class CoroutineStart {
4848
* Atomically (i.e., in a non-cancellable way) schedules the coroutine for execution according to its context.
4949
* This is similar to [DEFAULT], but the coroutine cannot be cancelled before it starts executing.
5050
*
51+
* The coroutine started with [ATOMIC] is guaranteed to start execution even if its [Job] was cancelled.
52+
* This [CoroutineStart] option can be used to ensure resources' disposal in case of cancellation.
53+
* For example, this `producer` guarantees that the `channel` will be eventually closed,
54+
* even if the coroutine scope is cancelled before `producer` is called:
55+
* ```
56+
* fun CoroutineScope.producer(channel: SendChannel<Int>) =
57+
* launch(start = CoroutineStart.ATOMIC) {
58+
* try {
59+
* // produce elements
60+
* } finally {
61+
* channel.close()
62+
* }
63+
* }
64+
* ```
65+
*
66+
* This is a **delicate** API. The coroutine starts execution even if its [Job] is cancelled before starting.
67+
* However, the resources used within a coroutine may rely on the cancellation mechanism,
68+
* and cannot be used after the [Job] cancellation. For instance, in Android development, updating a UI element
69+
* is not allowed if the coroutine's scope, which is tied to the element's lifecycle, has been cancelled.
70+
*
5171
* Cancellability of coroutine at suspension points depends on the particular implementation details of
5272
* suspending functions as in [DEFAULT].
5373
*/
54-
@ExperimentalCoroutinesApi // Since 1.0.0, no ETA on stability
74+
@DelicateCoroutinesApi
5575
ATOMIC,
5676

5777
/**

0 commit comments

Comments
 (0)