본문 바로가기

Android

Kotlin coroutine - Job or Deferred?

https://stackoverflow.com/questions/53428179/difference-between-job-and-deferred-in-coroutines-kotlin

 

Difference between Job and Deferred in Coroutines Kotlin

I am new to coroutines, I understand launch and async but still confusing part is deferred. What is deferred? and different between job and deferred.Clear explanation and Example is more helpful. T...

stackoverflow.com

 

Q: I am new to coroutines, I understand launch and async but still confusing part is deferred. What is deferred? and different between job and deferred. Clear explanation and Example is more helpful. Thanks in advance

 

- Marko Topolnik

 

Q 저는 코틀린을 처음 배우는데요, launch와 async는 알겠는데 아직 deferred 가 헷갈립니다. 그리고 job과 deferred 의 차이도 궁금합니다.

 

- 마르코 토폴닉

 


 

A: So job is sort of an object that represents a coroutine's execution and is related to  structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled.

From docs:

Job is a cancellable thing with a life-cycle that culminates in its completion.

Deferred is some kind of analog of Future in Java: in encapsulates an operation that will be finished at some point in future after it's initialization. But is also related to coroutines in Kotlin.

From documentation:

Deferred value is a non-blocking cancellable future — it is a Job that has a result.

So, Deferred is a Job that has a result:

A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.

An example:

somescope.launch {
    val userJob: Deferred = async(IO) { repository.getUser(id) }
    //some operations, while user is being retrieved 
    val user = userJob.await() //here coroutine will be suspended for a while, and the method `await` is available only from `Deferred` interface
    //do the job with retrieved user
}
Also, it is possible to structure this async request with an existing scope, but that is a talk of another question.

 

- Andrey Ilyunin

 

 

A: job은 코루틴의 실행을 표현하는 오브젝트 중 하나이고, 구조화된 동시성과 연관이 있습니다, 예를 들면 job은 취소될 수 있고, 이 경우에 job의 child job도 취소됩니다.

 

관련문서:

 

Job 은 취소 가능하고, 완료되면 라이프 사이클이 끝납니다.

Deferred 는 어떤 면에서 보면 Java 의 Future와 유사한 것인데, "초기화 된 이후" "미래의 어떤 시점에 종료될 예정인" "하나로 묶여진 명령"입니다. 하지만 또한 코틀린의 코루틴과 연관이 있습니다.

 

문서에 따르면:
Deferred 값은 논 블로킹 캔슬러블 future 입니다. 결과값을 가지고 있는 job 입니다.

즉, deferred는 결과값을 가지고 있는 job 입니다.

하나의 deferred의 값은 하나의 job 입니다. async builder의 coroutineContext안에 있는 하나의 job은 코루틴 자기자신을 가리킵니다.

 

- Andrey Ilyunin