[kotlin] 코루틴 조합하기
코틀린에서 코루틴은 비동기 프로그래밍을 쉽게 다룰 수 있게 해주는 강력한 도구입니다. 코루틴을 사용하면 콜백 지옥과 복잡한 스레드 처리를 피할 수 있으며 코드를 간결하게 작성할 수 있습니다. 코루틴을 사용하여 여러 비동기 작업을 조합하는 방법에 대해 살펴보겠습니다.
1. async
와 await
를 사용한 코루틴 조합
async
및 await
를 사용하여 여러 개의 코루틴을 조합할 수 있습니다. async
함수를 사용하여 각각의 비동기 작업을 시작하고 await
함수를 사용하여 결과를 기다릴 수 있습니다.
예를 들어, 다음은 두 개의 코루틴을 조합하는 간단한 예제입니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val result1 = async { getResult1() }
val result2 = async { getResult2() }
val combinedResult = result1.await() + result2.await()
println("Combined result: $combinedResult")
}
suspend fun getResult1(): Int {
delay(1000) // 가짜 비동기 작업
return 10
}
suspend fun getResult2(): Int {
delay(1500) // 가짜 비동기 작업
return 20
}
위 코드는 getResult1
및 getResult2
에서 각각의 결과를 얻어와 조합하여 출력합니다.
2. coroutineScope
를 사용한 코루틴 조합
coroutineScope
를 사용하여 여러 개의 코루틴을 조합할 수도 있습니다. coroutineScope
를 사용하면 모든 코루틴이 완료될 때까지 기다리고 조합된 결과를 반환할 수 있습니다.
다음은 coroutineScope
를 사용한 예제입니다.
import kotlinx.coroutines.*
suspend fun main() {
val combinedResult = coroutineScope {
val result1 = async { getResult1() }
val result2 = async { getResult2() }
result1.await() + result2.await()
}
println("Combined result: $combinedResult")
}
3. withContext
를 사용한 코루틴 조합
withContext
를 사용하여 다른 스레드에서 실행되는 코루틴을 조합할 수도 있습니다. 이를 통해 CPU 바운드 및 I/O 바운드 작업을 쉽게 조합할 수 있습니다.
예를 들어, 다음은 withContext
를 사용한 예제입니다.
import kotlinx.coroutines.*
fun main() = runBlocking {
val combinedResult = withContext(Dispatchers.Default) {
val result1 = getResult1()
val result2 = getResult2()
result1 + result2
}
println("Combined result: $combinedResult")
}
suspend fun getResult1(): Int {
delay(1000) // 가짜 비동기 작업
return 10
}
suspend fun getResult2(): Int {
delay(1500) // 가짜 비동기 작업
return 20
}
이렇게 여러가지 방법으로 코틀린의 코루틴을 조합하여 더욱 강력한 비동기 프로그래밍 코드를 작성할 수 있습니다.
더 자세한 내용은 Kotlin 공식 문서를 참고하세요.