Lee*_*eem 2 coroutine kotlin kotlin-coroutines
我正在尝试在 kotlin 协程中创建一个异步函数,这是我按照教程尝试的:
fun doWorkAsync(msg: String): Deferred<Int> = async {
delay(500)
println("$msg - Work done")
return@async 42
}
Run Code Online (Sandbox Code Playgroud)
但是在这段代码中async,编译器无法解决,但教程视频显示它运行良好。是不是因为教程使用了旧的 Kotlin 协程的做事方式?那么,如果是这样如何创建异步函数呢?
当协程具有实验性 API 时,可以只编写
async {
// your code here
}
Run Code Online (Sandbox Code Playgroud)
但是在稳定的 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
}
Run Code Online (Sandbox Code Playgroud)
或者
// 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
}
Run Code Online (Sandbox Code Playgroud)
或者
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
甚至
// 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2312 次 |
| 最近记录: |