Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Kotlin coroutine job.isActive in the calling method

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.

like image 780
Robin Avatar asked Oct 28 '25 09:10

Robin


1 Answers

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)
        }
    }
}
like image 58
Tenfour04 Avatar answered Oct 29 '25 23:10

Tenfour04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!