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

Rob*_*bin 3 android kotlin kotlin-coroutines

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

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

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

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想在此协程范围内复制函数的 impl 或将作业实例作为参数传递给该函数。处理此案的官方方式是什么?

非常感谢。

Ten*_*r04 7

创建complexFunOfReadingFile()一个suspend函数并在其中放入周期yield()ensureActive()调用。

例子:

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

  • 我添加了一个示例。如果您使用非内联的高阶函数,例如“File.forEachLine”,则您无权访问 lambda 内的协程上下文。`File.useLines` 是内联的。 (2认同)
  • 使用“return@withContext”,因为您位于 lambda 中。 (2认同)