Kotiln:Coroutine(3)

본 포스트의 내용은 kotlin weekly에서 소개 된 블로그의 내용을 개인적으로 정리하였습니다.

Cancel

코루틴이 하고 있는 작업은 취소가 가능합니다. 대신, 코루틴이 suspension point에 있을 때만 취소가 가능합니다.

Async Process 취소를 위한 방법

  1. launch builder가 리턴하는 Job 레퍼런스를 이용
  2. async()가 리턴하는 Deffered 레퍼런스 이용
    • cancel() 과 cancelandJoin() 함수를 이용할 수 있음
  3. Timeout 함수 사용
  4. withTimeoutOrNull 함수 사용
1. cancel()
2. join()
3. cancelAndJoin()
runBlocking {
    println("start main")

    val job = launch {
        repeat(300){waitingTime ->
                    println("Job is waiting $waitingTime...")
                    delay(50L)
                   }
    }

    delay(300L)

    println("Stop Waiting. Let's cancel it")
    job.cancel()
    job.join()
    println("end main")
}
4. withTimeout()
5. withTimeoutOrNull
runBlocking {
    withTimeout(1000L){
        repeat(50){ waitingTime ->
                   println("Job is waiting $waitingTime")
                   delay(100L)
                  }
    }
}

References