📌 Kotlin Coroutines에서 await
사용하기
1. 개요
Kotlin의 코루틴에서 await
함수는 Deferred
객체의 완료를 기다리면서도
기본 스레드를 차단하지 않는 비동기 대기 기능을 제공합니다.
이 함수는 Deferred
가 완료되면 그 값을 반환하며, 만약 Deferred
가 예외적으로 종료되었다면 예외를 던집니다.
2. 기본 사용법
다음은 await
를 활용하는 기본적인 예제입니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred: Deferred = async {
delay(1000L)
42
}
// 결과를 기다림
val result: Int = deferred.await()
println("Result: $result")
}
위 코드에서 async
함수는 새로운 코루틴을 시작하고, Deferred
객체를 반환합니다.
이후 await()
를 호출하면 코루틴의 결과를 기다린 후 반환합니다.
3. await
의 취소 가능성
await
함수는 취소가 가능한 함수입니다. 만약 현재 실행 중인 코루틴이 취소되면, await
도 즉시 CancellationException
을 던집니다.
다음은 await
가 취소될 수 있는 상황을 보여주는 예제입니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred = async {
delay(1000L)
42
}
delay(500L)
deferred.cancel() // 코루틴 취소
try {
println(deferred.await()) // CancellationException 발생
} catch (e: CancellationException) {
println("Job was cancelled: ${e.message}")
}
}
위 코드에서는 async
로 실행된 코루틴을 500ms 후 취소하였습니다.
await()
를 호출할 때 CancellationException
이 발생하여 정상적으로 종료됩니다.
4. 예외 처리
await
는 실행 중 발생한 예외를 호출자에게 전달합니다. 예외를 안전하게 처리하려면 try-catch
블록을 사용할 수 있습니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred = async {
delay(1000L)
throw Exception("Something went wrong")
}
try {
deferred.await()
} catch (e: Exception) {
println("Caught exception: ${e.message}")
}
}
위 예제에서는 async
내부에서 예외가 발생했으며, await()
를 호출할 때 예외가 전파됩니다.
try-catch
블록을 활용하여 예외를 적절히 처리할 수 있습니다.
📌 원본 출처
본 문서의 예제와 내용은 Kotlin 공식 문서를 참고하여 작성되었습니다. 자세한 내용은 아래 공식 문서를 통해 확인할 수 있습니다.
'Kotlin > kotlinx.coroutines' 카테고리의 다른 글
cancel (0) | 2025.02.07 |
---|---|
awaitCanellation (0) | 2025.02.07 |
awaitAll (0) | 2025.02.07 |
async (0) | 2025.02.06 |
asContextElement (0) | 2025.02.06 |