我对合作项目还不熟悉,我理解launchasync,但仍然让人困惑的是Deferred.Deferred是什么?JobDeferred之间的差异.清楚的解释和例子更有帮助.提前谢谢.

推荐答案

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.

Kotlin相关问答推荐

相当于roomdb中的DateTime Bigint列的是什么

数据源配置

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

如何从 Period.between() 返回的字符串中提取信息? (Kotlin )

mutableStateOf 和 mutableStateListOf 有什么区别?

如何在 Jetpack Compose 中启动和停止动画

判断 Kotlin 变量是否为函数

多个不同的指针输入

你怎么知道什么时候需要 yield()?

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

参考 Kotlin 中的 Java 接口静态字段

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

以编程方式重新启动 Spring Boot 应用程序/刷新 Spring 上下文

Kotlin如何分派invoke操作符?

如何为kotlin异常生成SerialVersionId?

Kotlin,什么时候按map授权?

Android Jetpack Compose 中的文本渐变

从 Kotlin 访问 Integer.class

如何在 spring-boot Web 客户端中发送请求正文?

任务':app:kaptDebugKotlin'的Kotlin执行失败