|
| 1 | +/* |
| 2 | + * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package kotlinx.coroutines.experimental |
| 6 | + |
| 7 | +import kotlin.coroutines.experimental.* |
| 8 | + |
| 9 | +@Suppress("FunctionName") |
| 10 | +public fun SupervisorJob(parent: Job? = null) : Job = SupervisorJobImpl(parent) |
| 11 | + |
| 12 | +public suspend fun <R> supervisorScope(block: suspend CoroutineScope.() -> R): R { |
| 13 | + // todo: optimize implementation to a single allocated object |
| 14 | + // todo: fix copy-and-paste with coroutineScope |
| 15 | + val owner = SupervisorCoroutine<R>(coroutineContext) |
| 16 | + owner.start(CoroutineStart.UNDISPATCHED, owner, block) |
| 17 | + owner.join() |
| 18 | + if (owner.isCancelled) { |
| 19 | + throw owner.getCancellationException().let { it.cause ?: it } |
| 20 | + } |
| 21 | + val state = owner.state |
| 22 | + if (state is CompletedExceptionally) { |
| 23 | + throw state.cause |
| 24 | + } |
| 25 | + @Suppress("UNCHECKED_CAST") |
| 26 | + return state as R |
| 27 | + |
| 28 | +} |
| 29 | + |
| 30 | +private class SupervisorJobImpl(parent: Job?) : JobSupport(true) { |
| 31 | + init { initParentJobInternal(parent) } |
| 32 | + override val onFailComplete get() = true |
| 33 | + override val handlesException: Boolean get() = false |
| 34 | + override fun childFailed(cause: Throwable): Boolean = false |
| 35 | +} |
| 36 | + |
| 37 | +private class SupervisorCoroutine<R>( |
| 38 | + parentContext: CoroutineContext |
| 39 | +) : AbstractCoroutine<R>(parentContext, true) { |
| 40 | + override fun childFailed(cause: Throwable): Boolean = false |
| 41 | +} |
0 commit comments