Kotlinx.coroutines: Not canceling jobs | completion on Delay

Created on 4 Nov 2019  路  4Comments  路  Source: Kotlin/kotlinx.coroutines

I declared a repeat(100) and for each index in body it create a job but that don't cancel each job when reach to end of loop.
I did read about coroutine when declare a scope for job to be canceled while this finish.
why job not cancel when finished??

  repeat(100) {
            val job = CoroutineScope(Dispatchers.Default).launch {
                val res = it * 1234
            }

            Log.i("TAG isActive", job.isActive.toString())
            Log.i("TAG isCompleted", job.isCompleted.toString())
            Log.i("TAG isCanceled", job.isCancelled.toString())
        }
question

Most helpful comment

  var j = CoroutineScope(IO).launch {
                textFileContext += response.await()
            }
            j.cancel()
            Log.d("tagxx", " is canceled -> "+j.isCancelled.toString())
            Log.d("tagxx", " is activated -> "+j.isActive.toString())
            Log.d("tagxx", " is completed -> "+j.isCompleted.toString())

I have the same exact issue

All 4 comments

  var j = CoroutineScope(IO).launch {
                textFileContext += response.await()
            }
            j.cancel()
            Log.d("tagxx", " is canceled -> "+j.isCancelled.toString())
            Log.d("tagxx", " is activated -> "+j.isActive.toString())
            Log.d("tagxx", " is completed -> "+j.isCompleted.toString())

I have the same exact issue

Hey, I know.
It's actually gets completed on isCompleted method after some kind of delay.
When we delayed process manually the logs shows that it is completed.

  this.window.decorView.postDelayed({
            Log.i("TAG isCompleted", job.isCompleted.toString())
        }, 1)

why job not cancel when finished?

Because a coroutine completes normally without exceptions and is not canceled externally.

Also, please note that your code contains data-race:

val job = CoroutineScope(Dispatchers.Default).launch {
    val res = it * 1234
}

Log.i("TAG isActive", job.isActive.toString()) // Here coroutine can still be active
Log.i("TAG isCompleted", job.isCompleted.toString()) // And here it can be already completed
Log.i("TAG isCanceled", job.isCancelled.toString()) // ... but never cancelled

So the possible outcomes are:
true false false, true true false and false, true, false

Does it answer your question? Can I close the issue?

Was this page helpful?
0 / 5 - 0 ratings