I am new to coroutines, I understand launch and async but still confusing part is Deferred. What is Deferred? and difference between Job and Deferred. Clear explanation and example is more helpful. Thanks in advance.
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
deferredvalue is aJob. Ajobin thecoroutineContextofasyncbuilder represents the coroutine itself.
An example:
someScope.launch {
val userJob: Deferred<User> = 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.