【问题标题】:How to check Kotlin coroutine job.isActive in the calling method如何在调用方法中检查 Kotlin 协程 job.isActive
【发布时间】:2020-07-09 14:05:11
【问题描述】:

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

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

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

但我的情况是我有一个非常复杂的 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
    }
}

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

非常感谢。

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    complexFunOfReadingFile() 设为suspend 函数并将定期yield()ensureActive() 调用放入其中。

    例子:

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

    【讨论】:

    • 谢谢,能给个样品吗?我尝试了 todo:suspend fun readFile(): Boolean{ while(str = readLine()) {ensureActive() //then process the str} } 但我在这个挂起函数中遇到错误:未解析的引用。由于接收器类型不匹配,以下候选者均不适用: public fun CoroutineContext.ensureActive():在 kotlinx.coroutines 中定义的单位 public fun CoroutineScope.ensureActive():在 kotlinx.coroutines 中定义的单位 public fun Job.ensureActive():单位在 kotlinx.coroutines 中定义
    • 我添加了一个示例。如果您使用非内联的高阶函数,例如File.forEachLine,则您无法访问 lambda 中的协程上下文。 File.useLines 是内联的。
    • 另一个与此相关的问题:如果我不使用“withContext(Dispatchers.IO)”包装我的文件 io 操作,我会收到“不适当的阻塞方法调用”IDE 警告。我是否必须包装它,因为我已经只从 CoroutineScope(Dispatchers.IO).launch {} 块调用它。我尝试用@Workthread注释挂起函数,警告仍然存在。
    • withContext(Dispatchers.IO) 中始终包装使用IO 的挂起函数是合适的,这样它们就可以在任何地方安全地使用。 IIRC,约定是任何挂起函数都应该可以安全地从主调度程序调用。我认为这就是发出警告的原因。但是,我偶尔会看到警告给出误报或漏报。
    • 使用 return@withContext,因为您在 lambda 中。
    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2020-01-10
    • 2019-12-06
    • 2020-06-07
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多