我对合作项目还不熟悉,我理解launch
和async
,但仍然让人困惑的是Deferred
.Deferred
是什么?Job
和Deferred
之间的差异.清楚的解释和例子更有帮助.提前谢谢.
我对合作项目还不熟悉,我理解launch
和async
,但仍然让人困惑的是Deferred
.Deferred
是什么?Job
和Deferred
之间的差异.清楚的解释和例子更有帮助.提前谢谢.
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:
工作是一件可以取消的事情,它的生命周期以完成为顶点.
Deferred
在Java中类似于Future
:in封装了一个操作,该操作将在初始化后的某个时间点完成.但也与Kotlin 的合作项目有关.
From documentation:
Deferred value is a non-blocking cancellable future — it is a Job that has a result.
所以,Deferred
是一个Job
,其结果是:
deferred
的值等于Job
.async
个构建器中的coroutineContext
个中的job
表示协同程序本身.
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.