36

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.

Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60

2 Answers2

30

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<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.

nyarian
  • 4,085
  • 1
  • 19
  • 51
  • Thanks llyunin, can explain with piece of code-snipets more helpful – Magesh Pandian Nov 22 '18 at 10:27
  • @MageshPandian, I've edited the answer. Also, `Deferred` interface is also extended with some another convenient methods, but they are for now marked as experimental (Kotlin 1.3) – nyarian Nov 22 '18 at 10:34
  • 1
    I think it's worth pointing out differences in [exception handling](https://kotlinlang.org/docs/reference/coroutines/exception-handling.html) which might be significant in some use cases; `launch` is throwing immediately while `async` throws exceptions as a "result" when calling `await()`. – Pawel Nov 22 '18 at 13:00
  • @Pawel There's yet another important point: `async` also immediately cancels its parent job, which then propagates cancellation to all other `async` tasks. This happens whether or not you `await` on it. You can prevent this by using `SupervisorJob` as a parent, but that would be abuse of the mechanism. – Marko Topolnik Nov 23 '18 at 09:22
18

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.
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436