• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 @file:JvmMultifileClass
6 @file:JvmName("JobKt")
7 @file:Suppress("DEPRECATION_ERROR", "RedundantUnitReturnType")
8 
9 package kotlinx.coroutines
10 
11 import kotlinx.coroutines.selects.*
12 import kotlin.coroutines.*
13 import kotlin.jvm.*
14 
15 // --------------- core job interfaces ---------------
16 
17 /**
18  * A background job. Conceptually, a job is a cancellable thing with a life-cycle that
19  * culminates in its completion.
20  *
21  * Jobs can be arranged into parent-child hierarchies where cancellation
22  * of a parent leads to immediate cancellation of all its [children] recursively.
23  * Failure of a child with an exception other than [CancellationException] immediately cancels its parent and,
24  * consequently, all its other children. This behavior can be customized using [SupervisorJob].
25  *
26  * The most basic instances of `Job` interface are created like this:
27  *
28  * * **Coroutine job** is created with [launch][CoroutineScope.launch] coroutine builder.
29  *   It runs a specified block of code and completes on completion of this block.
30  * * **[CompletableJob]** is created with a `Job()` factory function.
31  *   It is completed by calling [CompletableJob.complete].
32  *
33  * Conceptually, an execution of a job does not produce a result value. Jobs are launched solely for their
34  * side-effects. See [Deferred] interface for a job that produces a result.
35  *
36  * ### Job states
37  *
38  * A job has the following states:
39  *
40  * | **State**                        | [isActive] | [isCompleted] | [isCancelled] |
41  * | -------------------------------- | ---------- | ------------- | ------------- |
42  * | _New_ (optional initial state)   | `false`    | `false`       | `false`       |
43  * | _Active_ (default initial state) | `true`     | `false`       | `false`       |
44  * | _Completing_ (transient state)   | `true`     | `false`       | `false`       |
45  * | _Cancelling_ (transient state)   | `false`    | `false`       | `true`        |
46  * | _Cancelled_ (final state)        | `false`    | `true`        | `true`        |
47  * | _Completed_ (final state)        | `false`    | `true`        | `false`       |
48  *
49  * Usually, a job is created in the _active_ state (it is created and started). However, coroutine builders
50  * that provide an optional `start` parameter create a coroutine in the _new_ state when this parameter is set to
51  * [CoroutineStart.LAZY]. Such a job can be made _active_ by invoking [start] or [join].
52  *
53  * A job is _active_ while the coroutine is working or until [CompletableJob] is completed,
54  * or until it fails or cancelled.
55  *
56  * Failure of an _active_ job with an exception makes it _cancelling_.
57  * A job can be cancelled at any time with [cancel] function that forces it to transition to
58  * the _cancelling_ state immediately. The job becomes _cancelled_  when it finishes executing its work and
59  * all its children complete.
60  *
61  * Completion of an _active_ coroutine's body or a call to [CompletableJob.complete] transitions the job to
62  * the _completing_ state. It waits in the _completing_ state for all its children to complete before
63  * transitioning to the _completed_ state.
64  * Note that _completing_ state is purely internal to the job. For an outside observer a _completing_ job is still
65  * active, while internally it is waiting for its children.
66  *
67  * ```
68  *                                       wait children
69  * +-----+ start  +--------+ complete   +-------------+  finish  +-----------+
70  * | New | -----> | Active | ---------> | Completing  | -------> | Completed |
71  * +-----+        +--------+            +-------------+          +-----------+
72  *                  |  cancel / fail       |
73  *                  |     +----------------+
74  *                  |     |
75  *                  V     V
76  *              +------------+                           finish  +-----------+
77  *              | Cancelling | --------------------------------> | Cancelled |
78  *              +------------+                                   +-----------+
79  * ```
80  *
81  * A `Job` instance in the
82  * [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/coroutine-context.html)
83  * represents the coroutine itself.
84  *
85  * ### Cancellation cause
86  *
87  * A coroutine job is said to _complete exceptionally_ when its body throws an exception;
88  * a [CompletableJob] is completed exceptionally by calling [CompletableJob.completeExceptionally].
89  * An exceptionally completed job is cancelled and the corresponding exception becomes the _cancellation cause_ of the job.
90  *
91  * Normal cancellation of a job is distinguished from its failure by the type of this exception that caused its cancellation.
92  * A coroutine that threw [CancellationException] is considered to be _cancelled normally_.
93  * If a cancellation cause is a different exception type, then the job is considered to have _failed_.
94  * When a job has _failed_, then its parent gets cancelled with the exception of the same type,
95  * thus ensuring transparency in delegating parts of the job to its children.
96  *
97  * Note, that [cancel] function on a job only accepts [CancellationException] as a cancellation cause, thus
98  * calling [cancel] always results in a normal cancellation of a job, which does not lead to cancellation
99  * of its parent. This way, a parent can [cancel] its own children (cancelling all their children recursively, too)
100  * without cancelling itself.
101  *
102  * ### Concurrency and synchronization
103  *
104  * All functions on this interface and on all interfaces derived from it are **thread-safe** and can
105  * be safely invoked from concurrent coroutines without external synchronization.
106  *
107  * ### Not stable for inheritance
108  *
109  * **`Job` interface and all its derived interfaces are not stable for inheritance in 3rd party libraries**,
110  * as new methods might be added to this interface in the future, but is stable for use.
111  */
112 public interface Job : CoroutineContext.Element {
113     /**
114      * Key for [Job] instance in the coroutine context.
115      */
116     public companion object Key : CoroutineContext.Key<Job>
117 
118     // ------------ state query ------------
119 
120     /**
121      * Returns `true` when this job is active -- it was already started and has not completed nor was cancelled yet.
122      * The job that is waiting for its [children] to complete is still considered to be active if it
123      * was not cancelled nor failed.
124      *
125      * See [Job] documentation for more details on job states.
126      */
127     public val isActive: Boolean
128 
129     /**
130      * Returns `true` when this job has completed for any reason. A job that was cancelled or failed
131      * and has finished its execution is also considered complete. Job becomes complete only after
132      * all its [children] complete.
133      *
134      * See [Job] documentation for more details on job states.
135      */
136     public val isCompleted: Boolean
137 
138     /**
139      * Returns `true` if this job was cancelled for any reason, either by explicit invocation of [cancel] or
140      * because it had failed or its child or parent was cancelled.
141      * In the general case, it does not imply that the
142      * job has already [completed][isCompleted], because it may still be finishing whatever it was doing and
143      * waiting for its [children] to complete.
144      *
145      * See [Job] documentation for more details on cancellation and failures.
146      */
147     public val isCancelled: Boolean
148 
149     /**
150      * Returns [CancellationException] that signals the completion of this job. This function is
151      * used by [cancellable][suspendCancellableCoroutine] suspending functions. They throw exception
152      * returned by this function when they suspend in the context of this job and this job becomes _complete_.
153      *
154      * This function returns the original [cancel] cause of this job if that `cause` was an instance of
155      * [CancellationException]. Otherwise (if this job was cancelled with a cause of a different type, or
156      * was cancelled without a cause, or had completed normally), an instance of [CancellationException] is
157      * returned. The [CancellationException.cause] of the resulting [CancellationException] references
158      * the original cancellation cause that was passed to [cancel] function.
159      *
160      * This function throws [IllegalStateException] when invoked on a job that is still active.
161      *
162      * @suppress **This an internal API and should not be used from general code.**
163      */
164     @InternalCoroutinesApi
getCancellationExceptionnull165     public fun getCancellationException(): CancellationException
166 
167     // ------------ state update ------------
168 
169     /**
170      * Starts coroutine related to this job (if any) if it was not started yet.
171      * The result is `true` if this invocation actually started coroutine or `false`
172      * if it was already started or completed.
173      */
174     public fun start(): Boolean
175 
176 
177     /**
178      * Cancels this job with an optional cancellation [cause].
179      * A cause can be used to specify an error message or to provide other details on
180      * the cancellation reason for debugging purposes.
181      * See [Job] documentation for full explanation of cancellation machinery.
182      */
183     public fun cancel(cause: CancellationException? = null)
184 
185     /**
186      * @suppress This method implements old version of JVM ABI. Use [cancel].
187      */
188     @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
189     public fun cancel(): Unit = cancel(null)
190 
191     /**
192      * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [cancel].
193      */
194     @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
195     public fun cancel(cause: Throwable? = null): Boolean
196 
197     // ------------ parent-child ------------
198 
199     /**
200      * Returns a sequence of this job's children.
201      *
202      * A job becomes a child of this job when it is constructed with this job in its
203      * [CoroutineContext] or using an explicit `parent` parameter.
204      *
205      * A parent-child relation has the following effect:
206      *
207      * * Cancellation of parent with [cancel] or its exceptional completion (failure)
208      *   immediately cancels all its children.
209      * * Parent cannot complete until all its children are complete. Parent waits for all its children to
210      *   complete in _completing_ or _cancelling_ state.
211      * * Uncaught exception in a child, by default, cancels parent. This applies even to
212      *   children created with [async][CoroutineScope.async] and other future-like
213      *   coroutine builders, even though their exceptions are caught and are encapsulated in their result.
214      *   This default behavior can be overridden with [SupervisorJob].
215      */
216     public val children: Sequence<Job>
217 
218     /**
219      * Attaches child job so that this job becomes its parent and
220      * returns a handle that should be used to detach it.
221      *
222      * A parent-child relation has the following effect:
223      * * Cancellation of parent with [cancel] or its exceptional completion (failure)
224      *   immediately cancels all its children.
225      * * Parent cannot complete until all its children are complete. Parent waits for all its children to
226      *   complete in _completing_ or _cancelling_ states.
227      *
228      * **A child must store the resulting [ChildHandle] and [dispose][DisposableHandle.dispose] the attachment
229      * to its parent on its own completion.**
230      *
231      * Coroutine builders and job factory functions that accept `parent` [CoroutineContext] parameter
232      * lookup a [Job] instance in the parent context and use this function to attach themselves as a child.
233      * They also store a reference to the resulting [ChildHandle] and dispose a handle when they complete.
234      *
235      * @suppress This is an internal API. This method is too error prone for public API.
236      */
237     // ChildJob and ChildHandle are made internal on purpose to further deter 3rd-party impl of Job
238     @InternalCoroutinesApi
239     public fun attachChild(child: ChildJob): ChildHandle
240 
241     // ------------ state waiting ------------
242 
243     /**
244      * Suspends the coroutine until this job is complete. This invocation resumes normally (without exception)
245      * when the job is complete for any reason and the [Job] of the invoking coroutine is still [active][isActive].
246      * This function also [starts][Job.start] the corresponding coroutine if the [Job] was still in _new_ state.
247      *
248      * Note that the job becomes complete only when all its children are complete.
249      *
250      * This suspending function is cancellable and **always** checks for a cancellation of the invoking coroutine's Job.
251      * If the [Job] of the invoking coroutine is cancelled or completed when this
252      * suspending function is invoked or while it is suspended, this function
253      * throws [CancellationException].
254      *
255      * In particular, it means that a parent coroutine invoking `join` on a child coroutine throws
256      * [CancellationException] if the child had failed, since a failure of a child coroutine cancels parent by default,
257      * unless the child was launched from within [supervisorScope].
258      *
259      * This function can be used in [select] invocation with [onJoin] clause.
260      * Use [isCompleted] to check for a completion of this job without waiting.
261      *
262      * There is [cancelAndJoin] function that combines an invocation of [cancel] and `join`.
263      */
264     public suspend fun join()
265 
266     /**
267      * Clause for [select] expression of [join] suspending function that selects when the job is complete.
268      * This clause never fails, even if the job completes exceptionally.
269      */
270     public val onJoin: SelectClause0
271 
272     // ------------ low-level state-notification ------------
273 
274     /**
275      * Registers handler that is **synchronously** invoked once on completion of this job.
276      * When the job is already complete, then the handler is immediately invoked
277      * with the job's exception or cancellation cause or `null`. Otherwise, the handler will be invoked once when this
278      * job is complete.
279      *
280      * The meaning of `cause` that is passed to the handler:
281      * * Cause is `null` when the job has completed normally.
282      * * Cause is an instance of [CancellationException] when the job was cancelled _normally_.
283      *   **It should not be treated as an error**. In particular, it should not be reported to error logs.
284      * * Otherwise, the job had _failed_.
285      *
286      * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] the
287      * registration of this handler and release its memory if its invocation is no longer needed.
288      * There is no need to dispose the handler after completion of this job. The references to
289      * all the handlers are released when this job completes.
290      *
291      * Installed [handler] should not throw any exceptions. If it does, they will get caught,
292      * wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code.
293      *
294      * **Note**: Implementation of `CompletionHandler` must be fast, non-blocking, and thread-safe.
295      * This handler can be invoked concurrently with the surrounding code.
296      * There is no guarantee on the execution context in which the [handler] is invoked.
297      */
298     public fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle
299 
300     /**
301      * Registers handler that is **synchronously** invoked once on cancellation or completion of this job.
302      * when the job was already cancelled and is completed its execution, then the handler is immediately invoked
303      * with the job's cancellation cause or `null` unless [invokeImmediately] is set to false.
304      * Otherwise, handler will be invoked once when this job is cancelled or is complete.
305      *
306      * The meaning of `cause` that is passed to the handler:
307      * * Cause is `null` when the job has completed normally.
308      * * Cause is an instance of [CancellationException] when the job was cancelled _normally_.
309      *   **It should not be treated as an error**. In particular, it should not be reported to error logs.
310      * * Otherwise, the job had _failed_.
311      *
312      * Invocation of this handler on a transition to a _cancelling_ state
313      * is controlled by [onCancelling] boolean parameter.
314      * The handler is invoked when the job becomes _cancelling_ if [onCancelling] parameter is set to `true`.
315      *
316      * The resulting [DisposableHandle] can be used to [dispose][DisposableHandle.dispose] the
317      * registration of this handler and release its memory if its invocation is no longer needed.
318      * There is no need to dispose the handler after completion of this job. The references to
319      * all the handlers are released when this job completes.
320      *
321      * Installed [handler] should not throw any exceptions. If it does, they will get caught,
322      * wrapped into [CompletionHandlerException], and rethrown, potentially causing crash of unrelated code.
323      *
324      * **Note**: This function is a part of internal machinery that supports parent-child hierarchies
325      * and allows for implementation of suspending functions that wait on the Job's state.
326      * This function should not be used in general application code.
327      * Implementation of `CompletionHandler` must be fast, non-blocking, and thread-safe.
328      * This handler can be invoked concurrently with the surrounding code.
329      * There is no guarantee on the execution context in which the [handler] is invoked.
330      *
331      * @param onCancelling when `true`, then the [handler] is invoked as soon as this job transitions to _cancelling_ state;
332      *        when `false` then the [handler] is invoked only when it transitions to _completed_ state.
333      * @param invokeImmediately when `true` and this job is already in the desired state (depending on [onCancelling]),
334      *        then the [handler] is immediately and synchronously invoked and no-op [DisposableHandle] is returned;
335      *        when `false` then no-op [DisposableHandle] is returned, but the [handler] is not invoked.
336      * @param handler the handler.
337      *
338      * @suppress **This an internal API and should not be used from general code.**
339      */
340     @InternalCoroutinesApi
341     public fun invokeOnCompletion(
342         onCancelling: Boolean = false,
343         invokeImmediately: Boolean = true,
344         handler: CompletionHandler): DisposableHandle
345 
346     // ------------ unstable internal API ------------
347 
348     /**
349      * @suppress **Error**: Operator '+' on two Job objects is meaningless.
350      * Job is a coroutine context element and `+` is a set-sum operator for coroutine contexts.
351      * The job to the right of `+` just replaces the job the left of `+`.
352      */
353     @Suppress("DeprecatedCallableAddReplaceWith")
354     @Deprecated(message = "Operator '+' on two Job objects is meaningless. " +
355         "Job is a coroutine context element and `+` is a set-sum operator for coroutine contexts. " +
356         "The job to the right of `+` just replaces the job the left of `+`.",
357         level = DeprecationLevel.ERROR)
358     public operator fun plus(other: Job): Job = other
359 }
360 
361 /**
362  * Creates a job object in an active state.
363  * A failure of any child of this job immediately causes this job to fail, too, and cancels the rest of its children.
364  *
365  * To handle children failure independently of each other use [SupervisorJob].
366  *
367  * If [parent] job is specified, then this job becomes a child job of its parent and
368  * is cancelled when its parent fails or is cancelled. All this job's children are cancelled in this case, too.
369  * The invocation of [cancel][Job.cancel] with exception (other than [CancellationException]) on this job also cancels parent.
370  *
371  * Conceptually, the resulting job works in the same way as the job created by the `launch { body }` invocation
372  * (see [launch]), but without any code in the body. It is active until cancelled or completed. Invocation of
373  * [CompletableJob.complete] or [CompletableJob.completeExceptionally] corresponds to the successful or
374  * failed completion of the body of the coroutine.
375  *
376  * @param parent an optional parent job.
377  */
378 @Suppress("FunctionName")
379 public fun Job(parent: Job? = null): CompletableJob = JobImpl(parent)
380 
381 /** @suppress Binary compatibility only */
382 @Suppress("FunctionName")
383 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
384 @JvmName("Job")
385 public fun Job0(parent: Job? = null): Job = Job(parent)
386 
387 /**
388  * A handle to an allocated object that can be disposed to make it eligible for garbage collection.
389  */
390 public fun interface DisposableHandle {
391     /**
392      * Disposes the corresponding object, making it eligible for garbage collection.
393      * Repeated invocation of this function has no effect.
394      */
395     public fun dispose()
396 }
397 
398 // -------------------- Parent-child communication --------------------
399 
400 /**
401  * A reference that parent receives from its child so that it can report its cancellation.
402  *
403  * @suppress **This is unstable API and it is subject to change.**
404  */
405 @InternalCoroutinesApi
406 @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases")
407 public interface ChildJob : Job {
408     /**
409      * Parent is cancelling its child by invoking this method.
410      * Child finds the cancellation cause using [ParentJob.getChildJobCancellationCause].
411      * This method does nothing is the child is already being cancelled.
412      *
413      * @suppress **This is unstable API and it is subject to change.**
414      */
415     @InternalCoroutinesApi
parentCancellednull416     public fun parentCancelled(parentJob: ParentJob)
417 }
418 
419 /**
420  * A reference that child receives from its parent when it is being cancelled by the parent.
421  *
422  * @suppress **This is unstable API and it is subject to change.**
423  */
424 @InternalCoroutinesApi
425 @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases")
426 public interface ParentJob : Job {
427     /**
428      * Child job is using this method to learn its cancellation cause when the parent cancels it with [ChildJob.parentCancelled].
429      * This method is invoked only if the child was not already being cancelled.
430      *
431      * Note that [CancellationException] is the method's return type: if child is cancelled by its parent,
432      * then the original exception is **already** handled by either the parent or the original source of failure.
433      *
434      * @suppress **This is unstable API and it is subject to change.**
435      */
436     @InternalCoroutinesApi
437     public fun getChildJobCancellationCause(): CancellationException
438 }
439 
440 /**
441  * A handle that child keep onto its parent so that it is able to report its cancellation.
442  *
443  * @suppress **This is unstable API and it is subject to change.**
444  */
445 @InternalCoroutinesApi
446 @Deprecated(level = DeprecationLevel.ERROR, message = "This is internal API and may be removed in the future releases")
447 public interface ChildHandle : DisposableHandle {
448 
449     /**
450      * Returns the parent of the current parent-child relationship.
451      * @suppress **This is unstable API and it is subject to change.**
452      */
453     @InternalCoroutinesApi
454     public val parent: Job?
455 
456     /**
457      * Child is cancelling its parent by invoking this method.
458      * This method is invoked by the child twice. The first time child report its root cause as soon as possible,
459      * so that all its siblings and the parent can start cancelling their work asap. The second time
460      * child invokes this method when it had aggregated and determined its final cancellation cause.
461      *
462      * @suppress **This is unstable API and it is subject to change.**
463      */
464     @InternalCoroutinesApi
childCancellednull465     public fun childCancelled(cause: Throwable): Boolean
466 }
467 
468 // -------------------- Job extensions --------------------
469 
470 /**
471  * Disposes a specified [handle] when this job is complete.
472  *
473  * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
474  * ```
475  * invokeOnCompletion { handle.dispose() }
476  * ```
477  */
478 internal fun Job.disposeOnCompletion(handle: DisposableHandle): DisposableHandle =
479     invokeOnCompletion(handler = DisposeOnCompletion(handle).asHandler)
480 
481 /**
482  * Cancels the job and suspends the invoking coroutine until the cancelled job is complete.
483  *
484  * This suspending function is cancellable and **always** checks for a cancellation of the invoking coroutine's Job.
485  * If the [Job] of the invoking coroutine is cancelled or completed when this
486  * suspending function is invoked or while it is suspended, this function
487  * throws [CancellationException].
488  *
489  * In particular, it means that a parent coroutine invoking `cancelAndJoin` on a child coroutine throws
490  * [CancellationException] if the child had failed, since a failure of a child coroutine cancels parent by default,
491  * unless the child was launched from within [supervisorScope].
492  *
493  * This is a shortcut for the invocation of [cancel][Job.cancel] followed by [join][Job.join].
494  */
495 public suspend fun Job.cancelAndJoin() {
496     cancel()
497     return join()
498 }
499 
500 /**
501  * Cancels all [children][Job.children] jobs of this coroutine using [Job.cancel] for all of them
502  * with an optional cancellation [cause].
503  * Unlike [Job.cancel] on this job as a whole, the state of this job itself is not affected.
504  */
cancelChildrennull505 public fun Job.cancelChildren(cause: CancellationException? = null) {
506     children.forEach { it.cancel(cause) }
507 }
508 
509 /**
510  * @suppress This method implements old version of JVM ABI. Use [cancel].
511  */
512 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
cancelChildrennull513 public fun Job.cancelChildren(): Unit = cancelChildren(null)
514 
515 /**
516  * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [Job.cancelChildren].
517  */
518 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
519 public fun Job.cancelChildren(cause: Throwable? = null) {
520     children.forEach { (it as? JobSupport)?.cancelInternal(cause.orCancellation(this)) }
521 }
522 
523 // -------------------- CoroutineContext extensions --------------------
524 
525 /**
526  * Returns `true` when the [Job] of the coroutine in this context is still active
527  * (has not completed and was not cancelled yet).
528  *
529  * Check this property in long-running computation loops to support cancellation
530  * when [CoroutineScope.isActive] is not available:
531  *
532  * ```
533  * while (coroutineContext.isActive) {
534  *     // do some computation
535  * }
536  * ```
537  *
538  * The `coroutineContext.isActive` expression is a shortcut for `coroutineContext[Job]?.isActive == true`.
539  * See [Job.isActive].
540  */
541 public val CoroutineContext.isActive: Boolean
542     get() = this[Job]?.isActive == true
543 
544 /**
545  * Cancels [Job] of this context with an optional cancellation cause.
546  * See [Job.cancel] for details.
547  */
cancelnull548 public fun CoroutineContext.cancel(cause: CancellationException? = null) {
549     this[Job]?.cancel(cause)
550 }
551 
552 /**
553  * @suppress This method implements old version of JVM ABI. Use [CoroutineContext.cancel].
554  */
555 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
cancelnull556 public fun CoroutineContext.cancel(): Unit = cancel(null)
557 
558 /**
559  * Ensures that current job is [active][Job.isActive].
560  * If the job is no longer active, throws [CancellationException].
561  * If the job was cancelled, thrown exception contains the original cancellation cause.
562  *
563  * This method is a drop-in replacement for the following code, but with more precise exception:
564  * ```
565  * if (!job.isActive) {
566  *     throw CancellationException()
567  * }
568  * ```
569  */
570 public fun Job.ensureActive(): Unit {
571     if (!isActive) throw getCancellationException()
572 }
573 
574 /**
575  * Ensures that job in the current context is [active][Job.isActive].
576  *
577  * If the job is no longer active, throws [CancellationException].
578  * If the job was cancelled, thrown exception contains the original cancellation cause.
579  * This function does not do anything if there is no [Job] in the context, since such a coroutine cannot be cancelled.
580  *
581  * This method is a drop-in replacement for the following code, but with more precise exception:
582  * ```
583  * if (!isActive) {
584  *     throw CancellationException()
585  * }
586  * ```
587  */
ensureActivenull588 public fun CoroutineContext.ensureActive() {
589     get(Job)?.ensureActive()
590 }
591 
592 /**
593  * Cancels current job, including all its children with a specified diagnostic error [message].
594  * A [cause] can be specified to provide additional details on a cancellation reason for debugging purposes.
595  */
cancelnull596 public fun Job.cancel(message: String, cause: Throwable? = null): Unit = cancel(CancellationException(message, cause))
597 
598 /**
599  * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [CoroutineContext.cancel].
600  */
601 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
602 public fun CoroutineContext.cancel(cause: Throwable? = null): Boolean {
603     val job = this[Job] as? JobSupport ?: return false
604     job.cancelInternal(cause.orCancellation(job))
605     return true
606 }
607 
608 /**
609  * Cancels all children of the [Job] in this context, without touching the state of this job itself
610  * with an optional cancellation cause. See [Job.cancel].
611  * It does not do anything if there is no job in the context or it has no children.
612  */
cancelChildrennull613 public fun CoroutineContext.cancelChildren(cause: CancellationException? = null) {
614     this[Job]?.children?.forEach { it.cancel(cause) }
615 }
616 
617 /**
618  * @suppress This method implements old version of JVM ABI. Use [CoroutineContext.cancelChildren].
619  */
620 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
cancelChildrennull621 public fun CoroutineContext.cancelChildren(): Unit = cancelChildren(null)
622 
623 /**
624  * Retrieves the current [Job] instance from the given [CoroutineContext] or
625  * throws [IllegalStateException] if no job is present in the context.
626  *
627  * This method is a short-cut for `coroutineContext[Job]!!` and should be used only when it is known in advance that
628  * the context does have instance of the job in it.
629  */
630 public val CoroutineContext.job: Job get() = get(Job) ?: error("Current context doesn't contain Job in it: $this")
631 
632 /**
633  * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [CoroutineContext.cancelChildren].
634  */
635 @Deprecated(level = DeprecationLevel.HIDDEN, message = "Since 1.2.0, binary compatibility with versions <= 1.1.x")
636 public fun CoroutineContext.cancelChildren(cause: Throwable? = null) {
637     val job = this[Job] ?: return
638     job.children.forEach { (it as? JobSupport)?.cancelInternal(cause.orCancellation(job)) }
639 }
640 
Throwablenull641 private fun Throwable?.orCancellation(job: Job): Throwable = this ?: JobCancellationException("Job was cancelled", null, job)
642 
643 /**
644  * No-op implementation of [DisposableHandle].
645  * @suppress **This an internal API and should not be used from general code.**
646  */
647 @InternalCoroutinesApi
648 public object NonDisposableHandle : DisposableHandle, ChildHandle {
649 
650     override val parent: Job? get() = null
651 
652     /**
653      * Does not do anything.
654      * @suppress
655      */
656     override fun dispose() {}
657 
658     /**
659      * Returns `false`.
660      * @suppress
661      */
662     override fun childCancelled(cause: Throwable): Boolean = false
663 
664     /**
665      * Returns "NonDisposableHandle" string.
666      * @suppress
667      */
668     override fun toString(): String = "NonDisposableHandle"
669 }
670