TIL

8강 suspending function

suspending lambda

fun main(): Unit = runBlocking {
  launch {
    delay(100L)
  }
}

// launch의 시그니처
public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

suspend function의 활용

fun main(): Unit = runBlocking {
  val result1 = async {
    apiCall1() 
  }
  // val result1: Defferred<Int>
  
  val result2 = async {
    apiCall2(result1.await())
  }
  
  printWithThread(result2.await())
}

// apiCall1, apiCall2를 외부 라이브러리라 가정 (1초 걸림)
fun apiCall1(): Int { 
  Thread.sleep(1_000L)
  return 100
}

fun apiCall2(num: Int): Int {
  Thread.sleep(1_000L)
  return num * 2
}
fun main(): Unit = runBlocking {
  val result1 = apiCall1()
  val result2 = apiCall2(result1)
  
  printWithThread(result2)
}

suspend fun apiCall1(): Int {
  return CoroutineScope(Dispatchers.Default).async {
    Thread.sleep(1_000L)
    100
  }.await()
}

suspend fun apiCall2(num: Int): Int { // 여기선 CompletableFuture 사용
  return CompletableFuture.supplyAsync {
    Thread.sleep(1_000L)
    num * 2
  }.await() // 이 await는 코루틴이 만들어 놓은 확장함수이다.
}

추가적인 suspend 함수

fun main(): Unit = runBlocking {
  printWithThread("START")
  printWithThread(calculateResult())
  printWithThread("END")
}

suspend fun calculateResult(): Int = coroutineScope {
  val num1 = async {
    delay(1_000L)
    10 
  }
  
  val num2 = async {
    delay(1_000L)
    20
  }
  
  num1.await() + num2.await()
}

// 출력 결과 (launch 등과 달리 바로 실행되기에 30이 END 전에 출력된다.)
// START
// 30
// END
fun main(): Unit = runBlocking {
  printWithThread("START")
  printWithThread(calculateResult())
  printWithThread("END")
}

suspend fun calculateResult(): Int = withContext(Dispatchers.Default) {
  val num1 = async {
    delay(1_000L)
     10 
  }
  
  val num2 = async {
    delay(1_000L)
    20
  }
  
  num1.await() + num2.await()
}

// 출력 결과
// START
// 30
// END
fun main(): Unit = runBlocking {
  withTimeout(1_000L) {
    delay(1_500L)
    10 + 20 
  }
}

// 출력 결과
// Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms