如何启动不阻塞父函数返回且无需使用GlobalScope的协程?
方案1:将函数声明为CoroutineScope扩展函数(推荐)
该方案完全符合结构化并发规范,后台任务和调用方的生命周期绑定,不会出现任务泄露风险:
fun CoroutineScope.coroutiny(): String { launch(Dispatchers.IO) { delay(1000) println("Independent thing that should not avoid coroutiny to return") } return "Coroutiny return" } suspend fun main() = coroutineScope { println(coroutiny()) println("after coroutiny") delay(2000) }
运行后输出完全符合预期顺序。
方案2:保留suspend函数原生签名
如果受现有代码约束无法修改函数签名,可直接从当前suspend函数的上下文派生独立Scope启动后台任务:
suspend fun coroutiny(): String { // 从当前协程上下文派生独立Scope,新增Job用于和当前协程的生命周期解绑 val independentScope = CoroutineScope(coroutineContext + Job()) independentScope.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) }
如果需要后台任务跟随当前suspend函数的取消状态同步取消,去掉上下文中的+ Job()即可。
内容的提问来源于stack exchange,提问作者LeYAUable
相关产品推荐
相关产品推荐

