Composing suspending functions | Kotlin

일단 suspend functions을 알아보자.

(누군가는 보겠죠?)

suspend → 중지하다.유예하다

일단 코루틴 내의 코드는 일반 코드와 마찬가지로 순차 적인 동작 방식을 따릅니다.

다음과 같이 중요한 작업을 수행하는 기능이 2있습니다.

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")

The answer is 42
Completed in 2017 ms

두 suspend function을 실행하는 총 시간 2초로 순차적으로 작업했다는 것을 보여 주죠

근데 나는 동시에 실행해서 더 빠른 답을 얻고 싶어요. 그렇다면 async를 활용하면 됩니다. async의 개념은 launch와 마찬가지로 분리된 코루틴을 시작하고 이 코루틴은 다른 코루틴과 동시에 작동할 수 있는 가벼운 스레드입니다. 차이점은 launch는 job을 봔환하고 결과 값을 가지지 않고, async는 deferred라는 non-blocking future(작업?)을 반환하고 후에 결과를 제공하기로 합니다. Deferred 도 Job이기 떄문에 cancelable 합니다.

val time = measureTimeMillis {
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")

The answer is 42
Completed in 1017 ms
(async 비동기 처리 후 시간이 1초가 되었습니다.)

Lazily started async