I am trying to use Kotlin coroutine instead of legacy Java thread to perform background actions:
I learned from this link and it works fine
val job = launch {
    for(file in files) {
        ensureActive() //will throw cancelled exception to interrupt the execution
        readFile(file)
    }
}
But my case is that I have a very complex calling function of readFile(), how can I check whether the job is active inside that function?
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
    }
}
I don't want to copy the impl of the function inside this coroutine scope or pass the job instance as a parameter into that function. What is official way to handle this case?
Thanks a lot.
Make complexFunOfReadingFile() a suspend function and put periodic yield() or ensureActive() calls in it.
Example:
suspend fun foo(file: File) {
    file.useLines { lineSequence ->
        for (line in lineSequence) {
            yield() // or coroutineContext.ensureActive()            
            println(line)
        }
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With