【发布时间】:2021-12-19 16:18:01
【问题描述】:
我有一个函数应该完成它的工作,但也会触发一个后台进程。触发的进程,即使在函数中启动,也不应该阻止它返回,因为它与正在完成的工作没有直接关系。
代码示例:
suspend fun coroutiny(): String {
coroutineScope {
launch(Dispatchers.IO) {
delay(1000)
println("Independent thing that should not avoid coroutiny to return")
}
}
return "Coroutiny return"
}
suspend fun main() {
println(coroutiny())
println("after coroutiny")
delay(2000)
}
在这种情况下我想要的结果是:
Coroutiny return
after coroutiny
Independent thing that should not avoid coroutiny to return
但我得到的是:
Independent thing that should not avoid coroutiny to return
Coroutiny return
after coroutiny
我知道会发生这种情况,因为 coroutineScope {...} 仅在内部的协程返回/完成时返回。 我需要帮助的是知道如何在不求助于 GlobalScope.launch {...} 的情况下做我想做的事,我想避免这种情况,因为我的用例与记录在案的 GlobalScope 可接受的用例不匹配。
【问题讨论】:
标签: kotlin concurrency parallel-processing kotlin-coroutines