'How Kotlin's coroutine is cancelled under the hood?

Suppose we have a CoroutineScope and we launched several coroutines from it via launch. Then we do CoroutineScope.cancel(). And then we need to wait until cancellation finishes and all children of this scope will be canceled via job.join(). My questions are:

  1. On what factors does cancellation time depend? Can I reduce the time somehow?

I know that if the coroutine is calculating something, and does not check for cancellation, then it won't be canceled. But what if the coroutine is suspended? The coroutine will be canceled only when it "resumes"?

  1. When in my coroutine I collect values from the flow via flow.collect, and then I cancel coroutine, the coroutine will be canceled only when a new value will be emitted into the flow, yes? Or when the flow will be canceled?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source