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

标签 android kotlin kotlin-coroutines

我正在尝试使用 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/

相关文章:

spring-boot - 在 Spring Boot 中公开的 SQL 日志记录

android - 如何在 CoroutineWorker 中获取 WorkRequest Id

Kotlin 协程流程 : How to get the first item from a flow (i.文件元数据)并将其余项目作为内容流传递?

android - 切换到 'Main'协程并将其挂起以将结果发送回 'IO'协程

java - 使用 Java 将 GMT 时间转换为本地时间

android - 应用内结算 : Is ProductID and SubscriptionID the same?

android - 在android中可绘制的动态位图

android - snackbar 未出现在 viewpager 内的 fragment 布局/回收器 View 顶部

android - Firebase 中有没有一种方法可以自动将 id 列表交换到对象中

java - 方法的参数类型对应于扩展 super 内部类的内部类