- 중단은 코틀린 코루틴의 핵심임.
- 코루틴을 중단한다는 건 실행을 중간에 멈추는 것을 의미함.
- ex) 게임을 저장하고 저장된 시점부터 게임을 다시 시작
- 코루틴은
중단
되었을 때 Continuation
객체를 반환함.
- 이는 멈췄던 곳에서 다시 코루틴을 실행할 수 있음.
재개
- 작업을 재개하려면 코루틴이 필요함.
- 중단 함수는 반드시 코루틴(다른 중단 함수)에 의해 호출되어야 함.
suspend fun main() {
println("Before")
println("After")
}
// Before
// After
- Before와 After사이에서 중단하는 간단한 프로그램을 실행해보자.
- 두 지점 사이를 중단 지점으로 코틀린 라이브러리에서 제공하는
suspendCoroutine
함수를 사용해보자.
suspend fun main() {
println("Before")
suspendCoroutine<Unit> { }
println("After")
}
// Before
- 위 코드에서 After는 실행되지 않으며, 실행된 상태로 유지된다.
- 코루틴은 Before이후에 중단 후 재개되지 않음.
- 앞에서 언급했던 Continuation은 어디에 있을까?
- 밑에
suspendCoroutine
함수의 정의를 보자.
@InlineOnly
public suspend inline fun <T> suspendCoroutine(crossinline block: (Continuation<T>) -> Unit): T {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return suspendCoroutineUninterceptedOrReturn { c: Continuation<T> ->
val safe = SafeContinuation(c.intercepted())
block(safe)
safe.getOrThrow()
}
}
suspendCoroutine
함수는 일시 중단 함수내에서 Continuation
인스턴스를 획득하고 현재 실행중인 코루틴을 일시중단시킴.
suspendCoroutine
은 suspendCoroutineUninterceptedOrReturn
를 반환함.
- 이는 일시 중단 함수내에서 현재
Continuation
객체를 가져오고 현재 실행 중인 코루틴을 일시 중단하거나, 일시 중단 없이 즉시 결과를 반환함.
Continuation
객체를 인자로 받고, 인자로 들어간 람다는 중단되기 전에 실행된다.
suspend fun main() {
println("Before")
suspendCoroutine<Unit> { continuation ->
println("Before too") // 실행 후 중단.
}
println("After")
}
// Before
// Before too
suspendCoroutine
함수는 중단 되기 전에 Continuation
객체를 사용할 수 있다.
suspendCoroutine
이 호출된 뒤엔 이미 중단되어 Continuation
객체를 사용할 수 없음.
- 람다는
Continuation
객체를 저장한 뒤 코루틴을 다시 실행할 시점을 결정하기 위해 사용됨.
Continuation
객체를 이용해 코루틴을 중단한 후 곧바로 실행할 수 있음.