kotlin - 在 Kotlin 中创建异步函数

标签 kotlin coroutine kotlin-coroutines

我正在尝试在 kotlin 协程中创建一个异步函数,这是我按照教程尝试的:

fun doWorkAsync(msg: String): Deferred<Int> = async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

但在此代码中,编译器无法解析 async,但教程视频显示它运行良好。是因为本教程使用的是旧的 Kotlin 协程的做事方式吗?那么,如果是,如何创建异步函数呢?

最佳答案

当协程有实验性 API 时,可以只写

async {
    // your code here
}

但在稳定的 API 中,您应该提供一个 CoroutineScope 来运行协程。您可以通过多种方式做到这一点:

// should be avoided usually because you cannot manage the coroutine state. For example cancel it etc
fun doWorkAsync(msg: String): Deferred<Int> = GlobalScope.async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

// explicitly pass scope to run in
fun doWorkAsync(scope: CoroutineScope, msg: String): Deferred<Int> = scope.async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

// create a new scope inside outer scope
suspend fun doWorkAsync(msg: String): Deferred<Int> = coroutineScope {
    async {
        delay(500)
        println("$msg - Work done")
        return@async 42
    }
}

甚至

// extension function for your scrope to run like 'scope.doWorkAsync("Hello")'
fun CoroutineScope.doWorkAsync(msg: String): Deferred<Int> = async {
    delay(500)
    println("$msg - Work done")
    return@async 42
}

关于kotlin - 在 Kotlin 中创建异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770131/

相关文章:

java - Kotlin:从 java 访问嵌套枚举类

android - 此构建中使用了已弃用的 Gradle 功能,使其与 Gradle 5.0 不兼容

android - Kotlin接口(interface)无法实例化!接口(interface)名称 : kotlinx. 协程.Deferred

android - 在 Kotlin 协程中指定调度程序/上下文有多重要?如果你不指定它们会发生什么?

kotlin - 我对以下 Kotlin 声明感到困惑

kotlin - 在 `Pair<K,V>` 中指定 <K,V> 类型

内置函数上的 Python 协程

lua - 尝试在 Lua 中使用 MOAICoroutine 索引本地 'self'

kotlin - 返回 Kotlin 协程中生成的值

kotlin - 如何在不阻塞调用函数的情况下从另一个挂起函数调用挂起函数?