我正在尝试在 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/