gpt4 book ai didi

android - Coroutines Kotlin 中 Job 和 Deferred 的区别

转载 作者:IT老高 更新时间:2023-10-28 13:41:29 25 4
gpt4 key购买 nike

我是协程新手,我了解 launchasync 但仍然令人困惑的部分是 Deferred。什么是延迟JobDeferred 之间的区别。清晰的解释和示例更有帮助。提前致谢。

最佳答案

所以 job 是一种代表协程执行的对象,与 structured concurrency 相关。 ,例如您可以取消作业,该作业的所有子作业也将被取消。

来自 docs :

Job is a cancellable thing with a life-cycle that culminates in its completion.

Deferred 是 Java 中 Future 的某种模拟:in 封装了一个操作,该操作将在其初始化后的某个时间点完成。但也与 Kotlin 中的协程有关。

来自文档:

Deferred value is a non-blocking cancellable future — it is a Job that has a result.

所以,Deferred 是一个有结果的Job:

A deferred value is a Job. A job in the coroutineContext of async builder represents the coroutine itself.

一个例子:

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
}

此外,可以使用现有范围构造此 async 请求,但这是另一个问题的讨论。

关于android - Coroutines Kotlin 中 Job 和 Deferred 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com