CoroutineContext and ContinuationInterceptor (instead of dispatcher)

This commit is contained in:
Roman Elizarov
2017-01-13 21:01:57 +03:00
committed by Denis Zharkov
parent f611e39a69
commit 8d6a913cee
22 changed files with 507 additions and 148 deletions
@@ -23,25 +23,23 @@ abstract class CoroutineImpl(
arity: Int,
@JvmField
protected var completion: Continuation<Any?>?
) : DispatchedContinuation<Any?>, Lambda(arity), Continuation<Any?> {
) : Lambda(arity), Continuation<Any?> {
// label == -1 when coroutine cannot be started (it is just a factory object) or has already finished execution
// label == 0 in initial part of the coroutine
@JvmField
protected var label: Int = if (completion != null) 0 else -1
private val _dispatcher: ContinuationDispatcher? = (completion as? DispatchedContinuation<*>)?.dispatcher
private val _context: CoroutineContext? = completion?.context
override val dispatcher: ContinuationDispatcher?
get() = _dispatcher
override val context: CoroutineContext
get() = _context!!
private var _facade: Continuation<Any?>? = null
private var facade_: Continuation<Any?>? = null
val facade: Continuation<Any?> get() {
if (facade_ == null) {
facade_ = wrapContinuationIfNeeded(this, dispatcher)
}
return facade_!!
if (_facade == null) _facade = _context!![ContinuationInterceptor]?.interceptContinuation(this) ?: this
return _facade!!
}
override fun resume(value: Any?) {
@@ -66,7 +64,3 @@ abstract class CoroutineImpl(
protected abstract fun doResume(data: Any?, exception: Throwable?): Any?
}
internal interface DispatchedContinuation<in T> : Continuation<T> {
val dispatcher: ContinuationDispatcher?
}
@@ -17,34 +17,6 @@
package kotlin.jvm.internal
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationDispatcher
fun <T> normalizeContinuation(c: Continuation<T>): Continuation<T> {
if (c is CoroutineImpl) {
return c.facade
}
return c
}
internal fun <T> wrapContinuationIfNeeded(c: Continuation<T>, dispatcher: ContinuationDispatcher?): Continuation<T> {
if (dispatcher == null) return c
return DispatchedContinuationImpl(c, dispatcher)
}
private class DispatchedContinuationImpl<in T>(
private val c: Continuation<T>,
private val dispatcher: ContinuationDispatcher
) : Continuation<T> {
override fun resume(value: T) {
if (!dispatcher.dispatchResume(value, c)) {
c.resume(value)
}
}
override fun resumeWithException(exception: Throwable) {
if (!dispatcher.dispatchResumeWithException(exception, c)) {
c.resumeWithException(exception)
}
}
}
fun <T> normalizeContinuation(continuation: Continuation<T>): Continuation<T> =
(continuation as? CoroutineImpl)?.facade ?: continuation