coroutine 알아보기 (8) - Continuation
continuation
Continuation(연속성)
Continuation은 코루틴이 일시 중단(suspend)되었을 때, 나중에 어디에서 다시 실행해야 하는지를 나타내는 개념입니다. Kotlin에서 suspend
함수는 내부적으로 컴파일될 때 Continuation
객체를 인자로 받도록 변환됩니다.
즉, 코루틴은 실행을 멈추는 대신, 실행 상태를 Continuation
객체에 저장하고 필요할 때 다시 실행을 이어나갑니다.
Continuation의 역할
Continuation의 역할은 현재 실행 상태(스택, 변수 등)를 저장할 수 있으며, 일시 중단된 함수의 실행을 재개할 수 있고, 예외 처리 및 결과 반환 기능 제공을 제공합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
suspend fun simpleSuspendFunction(): String {
return suspendCoroutine { continuation ->
println("일시 중단됨")
continuation.resume("재개됨")
}
}
fun main() {
val continuation = suspend {
simpleSuspendFunction()
}.createCoroutine(object : Continuation<String> {
override val context: CoroutineContext = EmptyCoroutineContext
override fun resumeWith(result: Result<String>) {
println("코루틴 종료: ${result.getOrNull()}")
}
})
continuation.resume(Unit) // 코루틴 실행
}
// 일시 중단됨
// 코루틴 종료: 재개됨
suspendCoroutine
은 Continuation
을 활용하여 실행을 일시 중단하고, 특정 조건이 충족되면 다시 재개합니다.
createCoroutine
을 사용해 명시적으로 코루틴을 생성하고, resume(Unit)
을 호출하여 실행합니다.
resumeWith(result)
를 통해 최종 결과를 받을 수 있습니다.
정리
- Continuation은 코루틴의 실행 상태를 저장하고 필요할 때 다시 실행하는 핵심 역할을 합니다.
- Kotlin의
suspendCoroutine
을 이용하면 코루틴 내부에서Continuation
을 직접 다룰 수도 있습니다.
[출처]
- https://kotlinlang.org/docs/coroutines-overview.html
This post is licensed under CC BY 4.0 by the author.