본문 바로가기

Coroutines

[Coroutines] Job (status, cancel error handling)

✅ Job

코루틴의 Job은 기본적으로 백그라운드 작업이다.
이는 취소가 가능하고(Cancellable) 완료로 끝나는 수명주기를 가지고 있다. 또한 Parent Job을 취소하면 모든 Child Job이 재귀적으로 취소되는 Parent - Child계층구조로 정렬된다.

 

✅ Job의 6가지 상태

(New / Active / Completing / Cancelling/ Cancelled / Completed)

 

일반적으로 Job은 Active 상태에서 시작한다.

하지만 코루틴 빌더의 start매개변수를 CoroutineStart.LAZY로 지정한 경우 New상태에서 시작한다.

Job은 코루틴이 작동하는 동안 혹은 CompletableJob이 완료, 실패, 취소 될 때까지 Active 상태로 존재한다.

Active상태에 있는 Job이 Exception으로 인해 실패하면 Cancelled 상태로 전환된다. Job은 cancel() 함수를 이용하여 언제든지 취소상태로 전환시킬 수 있다.

코루틴 본문이 완료되거나 CompletableJob.complete이 호출될 경우 Job을 완료상태로 전환시킨다.

 

✅ Cancel

suspend fun jobTest() {  
    val firstJob = viewModelScope.launch {  
      delay(1000)  
    }  
    firstJob.cancel("Cause Of Cancel", InterruptedException("Force Cancel Job"))  
    println("${firstJob.getCancellationException()}")  
}

✅ Cancel 에러 핸들링

job이 cancel 되었을 때 exception별로 핸들링을 하고 싶을 때는 invokeOnComplete메서드를 이용하면 된다.

Job이 취소되었을 때 뿐만 아니라 완료되었을 때에도 throwable이 null값으로 넘어오면서 블록 내로 들어온다는 것을 주의해야한다.

suspend fun jobTest() {  
    val firstJob = viewModelScope.launch {  
        delay(1000)  
    }  
   firstJob.cancel("Cause Of Cancel",   InterruptedException("Force Cancel Job"))  
   firstJob.invokeOnCompletion {   
      when(it) {  
           is InterruptedException -> //Do on InterruptedException  
           null -> //Do on Complete   
       }  
    }  
}