繁体   English   中英

如何在调用方法中检查Kotlin协程job.isActive

[英]How to check Kotlin coroutine job.isActive in the calling method

我正在尝试使用 Kotlin 协程而不是传统的 Java 线程来执行后台操作:

我从这个链接中学到了,它工作正常

val job = launch {
    for(file in files) {
        ensureActive() //will throw cancelled exception to interrupt the execution
        readFile(file)
    }
}

但我的情况是我有一个非常复杂的调用 function 的 readFile(),我如何检查 function 中的作业是否处于活动状态?

val job = launch {
    for(file in files) {
        ensureActive() //will throw cancelled exception to interrupt the execution
        complexFunOfReadingFile(file) //may process each line of the file
    }
}

我不想在这个协程 scope 中复制 function 的 impl 或将作业实例作为参数传递到 function 中。 官方处理这种情况的方式是什么?

非常感谢。

complexFunOfReadingFile()设为suspend function 并在其中放入定期yield()ensureActive()调用。

例子:

suspend fun foo(file: File) {
    file.useLines { lineSequence ->
        for (line in lineSequence) {
            yield() // or coroutineContext.ensureActive()            
            println(line)
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM