📌 Kotlin Coroutines의 CancellableContinuation
이해하기
1. 개요
CancellableContinuation
는 코루틴의 일시 중단 지점을 나타내는 인터페이스로, 취소 가능성을 지원합니다. 이는 코루틴이 외부 콜백이나 비동기 작업과 상호 작용할 때 유용하게 사용됩니다.
2. 주요 기능
- 취소 지원: 코루틴의 작업이 취소되면, 해당
CancellableContinuation
도 취소되어CancellationException
을 발생시킵니다. - 스레드 안전성:
CancellableContinuation
는 스레드 안전하게 설계되어 여러 스레드에서 안전하게 사용할 수 있습니다. - 즉각적인 취소 보장: 코루틴이 일시 중단된 동안 취소되면, 이미
resume
이 호출되었더라도 코루틴은 성공적으로 재개되지 않습니다.
3. 사용 예시
외부 콜백 기반 API를 코루틴으로 변환할 때 suspendCancellableCoroutine
함수를 사용하여 CancellableContinuation
를 활용할 수 있습니다.
suspend fun CompletableFuture.await(): T = suspendCancellableCoroutine { continuation ->
this.whenComplete { result, throwable ->
if (throwable != null) {
continuation.resumeWithException(throwable)
} else {
continuation.resume(result)
}
}
continuation.invokeOnCancellation { this.cancel(true) }
}
위 예시에서, CompletableFuture
가 완료되면 결과나 예외를 통해 코루틴을 재개하거나 예외를 발생시킵니다. 또한, 코루틴이 취소되면 invokeOnCancellation
을 통해 CompletableFuture
도 취소됩니다.
4. 취소 시 리소스 정리
CancellableContinuation
는 취소 시 리소스를 안전하게 정리할 수 있도록 invokeOnCancellation
함수를 제공합니다.
suspendCancellableCoroutine { continuation ->
val resource = openResource()
continuation.invokeOnCancellation {
resource.close()
}
// ...
}
위 코드에서는 리소스를 열고, 코루틴이 취소될 경우 해당 리소스를 안전하게 닫습니다.
5. 상태 관리
CancellableContinuation
는 다음과 같은 세 가지 상태를 가집니다:
- Active: 초기 상태로, 작업이 진행 중입니다.
- Resumed: 작업이 완료되어 재개된 상태입니다.
- Canceled: 작업이 취소된 상태입니다.
📌 원본 출처
본 문서의 내용은 Kotlin 공식 문서를 참고하여 작성되었습니다. 자세한 내용은 아래 공식 문서를 통해 확인할 수 있습니다.
'Kotlin > kotlinx.coroutines' 카테고리의 다른 글
CompletableDeferred (0) | 2025.02.07 |
---|---|
CloseableCoroutineDispatcher (0) | 2025.02.07 |
cancelChildren (0) | 2025.02.07 |
cancelAndJoin (0) | 2025.02.07 |
cancel (0) | 2025.02.07 |