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 或将作业实例作为参数传递给该函数。处理此案的官方方式是什么?
非常感谢。
创建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)
| 归档时间: |
|
| 查看次数: |
1681 次 |
| 最近记录: |