Difference between Job and Deferred in Coroutines Kotlin
On a basic level, Deferred
is a future. It makes it possible for one coroutine to wait for the result produced by another one, suspending itself until it's ready. Calling async
is one way, but by far not the only way, to get a Deferred
.
However, I think your question is more about the basics: when to use launch
, when to use async-await
. Here's an important lesson: you probably don't need async. People tend to use it because the keywords async
and await
are familiar from other languages, but in Kotlin, async
is not a general-purpose tool to achieve non-blocking calls.
Here's a basic recipe on how to turn a blocking call into a suspending, non-blocking one:
uiScope.launch {
val ioResult = withContext(Dispatchers.IO) { blockingIOCall() }
... just use the result, you're on the GUI thread here.
}
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 aJob
. Ajob
in thecoroutineContext
ofasync
builder 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.