=================
== The Archive ==
=================

[Kotlin Coroutines] 3장. 중단은 어떻게 작동할까?

개요

재개

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@SinceKotlin("1.3")
public interface Continuation<in T> {
    /**
     * The context of the coroutine that corresponds to this continuation.
     */
    public val context: CoroutineContext

    /**
     * Resumes the execution of the corresponding coroutine passing a successful or failed [result] as the
     * return value of the last suspension point.
     */
    public fun resumeWith(result: Result<T>)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
suspend fun main() { // <- suspend 가 붙은 main
    println("Before")

    suspendCoroutine { continuation -> // <- 여기서 중단!
        println("Before too")
        continuation.resume(Unit) // <- 중단 이후 바로 재개
    }

    println("After") // <- resume 을 호출 했기 때문에 출력 가능
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
suspend fun main() { // <- suspend 가 붙은 main
    println("Before")

    suspendCoroutine { continuation -> // <- 여기서 중단!
        thread {
            println("Suspended")
            Thread.sleep(1000)
            continuation.resume(Unit)
            println("Resumed") // <- resume 이후 바로 실행이 되지는 않음, After 이후 출력
        }
    }

    println("After") // <- 1초 후 바로 출력
}

값으로 재개하기

예외로 재개하기

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
private class MyException : Throwable("Just an exception")

suspend fun main() {
    try {
        suspendCoroutine<Unit> { cont ->
            cont.resumeWithException(MyException())
        }
    } catch (e: MyException) {
        println("Caught!")
    }
}

함수가 아닌 코루틴을 중단시킨다

요약