【问题标题】:How to call suspend function in gradle task?如何在 gradle 任务中调用挂起函数?
【发布时间】:2022-01-18 10:06:38
【问题描述】:

我尝试了以下代码,但任务在响应到达之前完成:

buildscript {
    dependencies {
        classpath("io.ktor:ktor-client-core:1.6.5")
        classpath("io.ktor:ktor-client-cio:1.6.5")
    }
}

tasks {
    register("suspendCall") {
        doLast {
            kotlinx.coroutines.GlobalScope.launch {
                val client = io.ktor.client.HttpClient()
                val response = client.get<io.ktor.client.statement.HttpResponse>("https://ktor.io/")
                println(response)
            }
        }
    }
}

是否有等待异步代码完成的正确方法?

【问题讨论】:

    标签: gradle kotlin-coroutines gradle-kotlin-dsl


    【解决方案1】:

    据我所知,要异步或并行工作,您需要使用Worker API

    Worker API 能够将任务操作的执行分解为离散的工作单元,然后并发和异步执行该工作。这允许 Gradle 充分利用可用资源并更快地完成构建。

    因此,您应该不需要使用特定语言的异步概念,例如 Kotlin 的协程。相反,您可以使用普通的 Kotlin 或 Java,让 Gradle 处理异步位。

    【讨论】:

    • 感谢您的回答! Worker API 绝对可以解决这个任务。但是有没有办法使用 WorkerExecutor 作为协程上下文?在 build.gradle.kts 脚本中描述任务会更容易,而不是在 buildSrc 中使用所有注入的参数。
    • @Nolequen 您也许可以创建自己的调度程序,该调度程序连接到 Worker API kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/…
    猜你喜欢
    • 2018-12-10
    • 2016-08-11
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2020-04-13
    • 2013-08-24
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多