Skip to content

Commit

Permalink
Change the contract of CoroutineContext.isActive to return 'true' for…
Browse files Browse the repository at this point in the history
… contexts with no job in it. (#3639)

Otherwise, the API is becoming an error prone for being called from jobless entrypoints (i.e. 'suspend fun main' or Ktor handlers), as 'if (ctx.isActive)' is a well-established pattern for busy-wait or synchronous job.
It is now aligned with CoroutineScope.isActive behaviour.

Fixes #3300
  • Loading branch information
qwwdfsad authored Feb 23, 2023
1 parent 1ed19c8 commit 747db9e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
6 changes: 3 additions & 3 deletions kotlinx-coroutines-core/common/src/Job.kt
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ public fun Job.cancelChildren(cause: Throwable? = null) {

/**
* Returns `true` when the [Job] of the coroutine in this context is still active
* (has not completed and was not cancelled yet).
* (has not completed and was not cancelled yet) or the context does not have a [Job] in it.
*
* Check this property in long-running computation loops to support cancellation
* when [CoroutineScope.isActive] is not available:
Expand All @@ -550,11 +550,11 @@ public fun Job.cancelChildren(cause: Throwable? = null) {
* }
* ```
*
* The `coroutineContext.isActive` expression is a shortcut for `coroutineContext[Job]?.isActive == true`.
* The `coroutineContext.isActive` expression is a shortcut for `get(Job)?.isActive ?: true`.
* See [Job.isActive].
*/
public val CoroutineContext.isActive: Boolean
get() = this[Job]?.isActive == true
get() = get(Job)?.isActive ?: true

/**
* Cancels [Job] of this context with an optional cancellation cause.
Expand Down
11 changes: 11 additions & 0 deletions kotlinx-coroutines-core/common/test/CoroutineScopeTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -277,4 +277,15 @@ class CoroutineScopeTest : TestBase() {

private fun scopePlusContext(c1: CoroutineContext, c2: CoroutineContext) =
(ContextScope(c1) + c2).coroutineContext

@Test
fun testIsActiveWithoutJob() {
var invoked = false
suspend fun testIsActive() {
assertTrue(coroutineContext.isActive)
invoked = true
}
::testIsActive.startCoroutine(Continuation(EmptyCoroutineContext){})
assertTrue(invoked)
}
}

0 comments on commit 747db9e

Please sign in to comment.