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.