为什么Success(kotlin.Unit)只出现了1次而不是2次?


#1

代码如下

suspend fun suspendFunc02(a: String, b: String)
        = suspendCoroutine<Int> { continuation ->
    thread {
        continuation.resumeWith(Result.success(5)) // ... ①
    }
}


class LogInterceptor : ContinuationInterceptor {
    override val key = ContinuationInterceptor

    override fun <T> interceptContinuation(continuation: Continuation<T>) =
        LogContinuation(continuation)
}

class LogContinuation<T>(private val continuation: Continuation<T>) :
    Continuation<T> by continuation {
    override fun resumeWith(result: Result<T>) {
        println("before resumeWith: $result")
        continuation.resumeWith(result)
        println("after resumeWith.")
    }
}

fun main() {
    suspend {
        suspendFunc02("Hello", "Kotlin")
        suspendFunc02("Hello", "Coroutine")
    }.startCoroutine(object : Continuation<Int> {
        override val context = LogInterceptor()

        override fun resumeWith(result: Result<Int>) {
            result.getOrThrow()
        }
    })
}

输出

before resumeWith: Success(kotlin.Unit)
after resumeWith.
before resumeWith: Success(5)
after resumeWith.
before resumeWith: Success(5)
after resumeWith.

问题1:为什么Success(kotlin.Unit)只出现了1次而不是2次?


还有就是如果我把suspendFunc02方法改为如下

suspend fun suspendFunc02(a: String, b: String)
        = suspendCoroutine<Int> { continuation ->
    continuation.resumeWith(Result.success(5)) // ... ①
}

输出就会变为

before resumeWith: Success(kotlin.Unit)
after resumeWith.

问题2:上面的输出为什么没有下面的文字?

before resumeWith: Success(5)
after resumeWith.

#2

第一次应该是协程启动时,通过回调调用开始执行协程体的时候调用的
可以通过如下的代码验证

suspend {
println(“HELLO”)
100
}.startCoroutine(object : Continuation<Int> {
override val context = LogInterceptor()
override fun resumeWith(result: Result<Int>) {
println(“startCoroutine”)
result.getOrThrow()
}
})

在打印HELLO之前,先打印了 before resumeWith: Success(kotlin.Unit)


#3

懂了谢谢


京ICP备16022265号-2 Kotlin China 2017 - 2018