TIL

4강 코루틴 취소

코루틴을 취소하는 방법

취소에 협조하는 방법1. suspend 함수 호출

fun main(): Unit = runBlocking {
  val job1 = launch {
    delay(1_000L)
    printWithThread("Job 1")
  }
  val job2 = launch {
    delay(1_000L)
    printWithThread("Job 2")
  }
  delay(100L) // 첫번째 코루틴 실행을 잠시 기다린다.
  job1.cancel()
}
// 실행 결과
// [main @coroutine#3] Job 2
fun main(): Unit = runBlocking {
  val job = launch {
    delay(10L)
    printWithThread("Job 1")
  }
  delay(100L)
  job.cancel()
}
// 실행 결과
// [main @coroutine#2] Job 1

취소에 협조하는 방법2. isActive로 직접 상태를 확인해 CancellationException을 던지기

fun main(): Unit = runBlocking {
  val job = launch(Dispatchers.Default) {
    var i = 1
    var nextPrintTime = System.currentTimeMillis() // 현재 시각
    while (i <= 5) { // 5번 반복
      if (nextPrintTime <= System.currentTimeMillis()) {
        printWithThread("${i++}번째 출력")
        nextPrintTime += 1_000L // 1초 후에 다시 출력되도록
        
      if (!isActive) { //
        throw CancellationException()
      }
    }
  }
  delay(100L)
  printWithThread("취소 시작")
  job.cancel()
}

// 실행 결과
// [DefaultDispatcher-worker-1 @coroutine#2] 1        !
// [main @coroutine#1] 취소 시작
  
fun main(): Unit = runBlocking {
  val job = launch {
    try {
      delay(1_000L)
    } catch (e: CancellationException) { // 예외 무시
    }
    printWithThread("delay에 의해 취소되지 않음")
  }
  
  delay(100L)
  printWithThread("취소 시작")
  job.cancel()
}

// 실행 결과
// [main @coroutine#1] 취소 시작
// [main @coroutine#2] delay에 의해 취소되지 않음