Skip to content

Commit 5c44afb

Browse files
elizarovqwwdfsad
authored andcommitted
Implicitly add Job in CoroutineScope constructor if it is missing
This way creating custom scopes via `CoroutineScope` is conceptually similar to `coroutineScope { ... }` constructor. Fixes #610
1 parent f307159 commit 5c44afb

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public interface CoroutineScope {
8383
* This is a shorthand for `CoroutineScope(thisScope + context)`.
8484
*/
8585
public operator fun CoroutineScope.plus(context: CoroutineContext): CoroutineScope =
86-
CoroutineScope(coroutineContext + context)
86+
ContextScope(coroutineContext + context)
8787

8888
/**
8989
* Returns `true` when current [Job] is still active (has not completed and was not cancelled yet).
@@ -198,7 +198,12 @@ public suspend inline fun <R> currentScope(block: CoroutineScope.() -> R): R =
198198
CoroutineScope(coroutineContext).block()
199199

200200
/**
201-
* Creates [CoroutineScope] that wraps the given [coroutineContext].
201+
* Creates [CoroutineScope] that wraps the given coroutine [context].
202+
*
203+
* If the given [context] does not contain a [Job] element, then a default `Job()` is created.
204+
* This way, cancellation or failure or any child coroutine in this scope cancels all the other children,
205+
* just like inside [coroutineScope] block.
202206
*/
203207
@Suppress("FunctionName")
204-
public fun CoroutineScope(context: CoroutineContext): CoroutineScope = ContextScope(context)
208+
public fun CoroutineScope(context: CoroutineContext): CoroutineScope =
209+
ContextScope(if (context[Job] != null) context else context + Job())

common/kotlinx-coroutines-core-common/test/CoroutineScopeTest.kt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
package kotlinx.coroutines.experimental
66

7+
import kotlinx.coroutines.experimental.internal.*
78
import kotlin.coroutines.experimental.*
89
import kotlin.test.*
910

@@ -205,5 +206,5 @@ class CoroutineScopeTest : TestBase() {
205206
}
206207

207208
private fun scopePlusContext(c1: CoroutineContext, c2: CoroutineContext) =
208-
(CoroutineScope(c1) + c2).coroutineContext
209+
(ContextScope(c1) + c2).coroutineContext
209210
}

0 commit comments

Comments
 (0)