我正在尝试使用 Kotlin 协程而不是传统的 Java 线程来执行后台操作:
我从中学到了link而且效果很好
val job = launch {
for(file in files) {
ensureActive() //will throw cancelled exception to interrupt the execution
readFile(file)
}
}
但我的情况是我有一个非常复杂的 readFile() 调用函数,我如何检查该函数中的作业是否处于 Activity 状态?
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
}
}
我不想在这个协程范围内复制函数的 impl 或将作业实例作为参数传递给该函数。 官方的处理方式是什么?
非常感谢。
最佳答案
使 complexFunOfReadingFile()
成为一个 suspend
函数并定期调用 yield()
或 ensureActive()
调用它。
例子:
suspend fun foo(file: File) {
file.useLines { lineSequence ->
for (line in lineSequence) {
yield() // or coroutineContext.ensureActive()
println(line)
}
}
}
关于android - 如何在调用方法中检查 Kotlin 协程 job.isActive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62816696/