본문 바로가기

Kotlin/kotlinx.coroutines

async

📌 Kotlin Coroutines에서 async 사용하기

1. 개요

Kotlin의 async 함수는 새로운 코루틴을 생성하고, 그 결과를 Deferred 객체로 반환합니다. 이를 활용하면 비동기 작업을 수행한 후, 결과를 나중에 사용할 수 있습니다.

async로 실행된 코루틴은 즉시 실행되며, await() 함수를 호출하여 결과를 가져올 수 있습니다. 또한 start 매개변수를 CoroutineStart.LAZY로 설정하면 지연 실행이 가능합니다.

2. 기본 사용법

다음은 async를 활용하는 기본적인 예제입니다.


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. 지연 실행 (Lazy Start)

기본적으로 async는 즉시 실행됩니다. 그러나 CoroutineStart.LAZY를 사용하면 start()를 호출하거나 await()를 처음 호출할 때까지 실행되지 않습니다.


import kotlinx.coroutines.*

fun main() = runBlocking {
    val deferred: Deferred = async(start = CoroutineStart.LAZY) {
        delay(1000L)
        42
    }

    println("Before start")
    deferred.start() // 수동으로 시작
    val result: Int = deferred.await()
    println("Result: $result")
}

위 코드에서는 asyncCoroutineStart.LAZY로 설정하여 지연 실행을 적용하였습니다. deferred.start()를 호출하기 전까지 코루틴이 실행되지 않습니다.

4. 구조적 동시성과 예외 처리

async 함수로 생성된 코루틴은 **구조적 동시성(Structured Concurrency)**을 따르며, 부모 코루틴이 취소되면 자식 코루틴도 함께 취소됩니다.

예제 코드를 살펴보겠습니다.


import kotlinx.coroutines.*

fun main() = runBlocking {
    val scope = CoroutineScope(Job())

    val deferred = scope.async {
        delay(1000L)
        throw Exception("Something went wrong")
    }

    try {
        deferred.await()
    } catch (e: Exception) {
        println("Caught exception: ${e.message}")
    }
}

위 예제에서는 async를 실행한 후 예외가 발생하였을 때 try-catch를 사용하여 예외를 처리하고 있습니다. async 내부에서 예외가 발생하더라도 프로그램이 충돌하지 않고 안전하게 종료됩니다.

📌 원본 출처

본 문서의 예제와 내용은 Kotlin 공식 문서를 참고하여 작성되었습니다. 자세한 내용은 아래 공식 문서를 통해 확인할 수 있습니다.

🔗 Kotlin Coroutines 공식 문서 - async

'Kotlin > kotlinx.coroutines' 카테고리의 다른 글

cancel  (0) 2025.02.07
awaitCanellation  (0) 2025.02.07
awaitAll  (0) 2025.02.07
await  (0) 2025.02.07
asContextElement  (0) 2025.02.06