https://kotlinlang.org/docs/composing-suspending-functions.html
Composing suspending functions | Kotlin
kotlinlang.org
suspending function
suspend fun doSomethingUsefulOne(): Int {
delay(1000L) // pretend we are doing something useful here
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // pretend we are doing something useful here, too
return 29
}
val time = measureTimeMillis {
val one = doSomethingUsefulOne()
val two = doSomethingUsefulTwo()
println("The answer is ${one + two}")
}
println("Completed in $time ms")
코루틴에서는 기본적으로 suspending 함수들을 순차적으로 수행한다.
async
async 키워드를 통해 동시에 수행을 가능하게 할 수 있다. launch와 유사하게 동시에 다른 블록을 수행하지만 launch는 Job을 반환하여 Job을 취소할 수 있도록 하지만 async는 Job과 결과값도 받을 수 있다. await를 통해 받을 수 있다.
val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
suspend 함수를 async 블록내에서 불러내어서 두 개의 suspend 함수를 동시에 수행하는 것과 async 블록에서 결과값을 받기위해 await()를 사용하는 것을 확인할 수 있다.
Lazily started async
async(start = CoroutineStart.LAZY)를 통해 언제 수행할지 정할 수 있다.
val time = measureTimeMillis {
val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() }
val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() }
// some computation
one.start() // start the first one
two.start() // start the second one
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
async 코루틴을 start() 메소드를 통해 실행시킬 수 있다.
async를 이용한 구조적인 동시성
예외가 발생하면 구조적인 계층에 따라 취소가 전파된다.
'Kotlin > 공부노트' 카테고리의 다른 글
Coroutine - 4. Cancel, isActive (0) | 2022.03.24 |
---|---|
Coroutine - 3. job, join (0) | 2022.03.17 |
Coroutine - 2. Structured concurrency, suspend, coroutineScope (0) | 2022.03.12 |
Coroutine - 1. launch, runBlocking, delay (0) | 2022.03.10 |
댓글