IT/Kotlin

Coroutine Job과 Scope

물통꿀꿀이 2020. 11. 22. 15:33

Job

Job은 life-cycle이 있는 cancellable 값?? 인터페이스 이다. 즉, 코루틴 context에 존재하는 여러 값 중 하나로 외부에 의해 언제든 중단이 가능한 값이다. (join 이나 cancel을 통해서..)

 

Job을 구현하는 인터페이스는 2개 정도로 볼 수 있는데, Coroutine job과 CompletableJob이 있다.

1) Coroutine job은 launch 코루틴 빌더에 의해서 생성

2) CompletableJob은 Job() factory에 의해서 생성된다.

그런데 Job 특성이 코루틴 block을 실행시지만 결과값을 주진 않는다. (값을 얻기 위해서는 Deferred를..)

 

Job State

Job의 내부 상태는 위의 그림과 같다.

코루틴의 시점마다 상태가 다를 수 있지만, 간단히 빌더에 의해 생성될 때 Active 상태라고 생각하면 된다.

또한 코루틴 context에서 볼 수 있는 job은 "코루틴 == job" 으로 이해 하면 될 것 같다.

Scope

코루틴은 coroutineScope 빌더 (아래 공식 문서 확인)를 통해 scope를 만들 수 있다. scope를 만들면 runBlocking과 같이 내부 코루틴이 완료될 때까지 scope는 유지 된다.

This function is designed for parallel decomposition of work. When any child coroutine in this scope fails, this scope fails and all the rest of the children are cancelled (for a different behavior see supervisorScope). This function returns as soon as the given block and all its children coroutines are completed.