androidkotlinkotlin-coroutines

Job.cancel() does not cancel coroutine


I have a small test like this. suppose the getAll() function is getting data from api. I use the delay(3000) function to simulate the delay.

class Repository {
    var job: Job? = null
    fun getAll() {
        job = CoroutineScope(Dispatchers.IO).launch {
            try {
                delay(3000)
                println("getAll oke")
            } catch (e: Exception) {
                println("CancellationException")
            }
        }
    }

    fun cancel() {
        job?.cancel()
        println("cancel")
    }
}

fun main() {
    runBlocking {
        val api = Repository()
        launch {
            api.getAll()
        }
        delay(1000)
        api.cancel()
        delay(5000)
        println("END")
    }
}

In the above paragraph it will print out like this:

cancel
CancellationException
END

If I replace delay(3000) with Thread.sleep(3000).

cancel
getAll oke
END

Problem: If I replace delay(3000) with Thread.sleep(3000). It not work. I can explain. The reason is because delay() knows whether the coroutine has been called cancel() or not. If it has been canceled, it will automatically cancel that coroutine.

But Thread.sleep() does not. So even though cancel() has been called. the statements in the coroutine will still run.

My question is. If the getAll() function makes an Api call using retrofit, room... will it be canceled when cancel is called?


Solution

  • Cancellations in coroutines are cooperative. This means the coroutine has to cooperate to be properly cancelled, it has to check the cancellation status in regular intervals and throw if needed. Thread.sleep is not at all aware of coroutines, so it simply ignores cancellations. Same if we do a blocking I/O or CPU-heavy computation (without additional checks) - they can't be cancelled.

    There is no generic answer to the question if 3rd party libraries properly handle cancellations. Most of good and popular libraries designed for coroutines should support cancellations - this includes Retrofit and Room. But you need to check the documentation of a given library to make sure.