Sobes.tech
Middle+

Are there cases when we cannot cancel coroutines?

sobes.tech AI

Answer from AI

Yes, they exist.

Examples of such cases:

  • A coroutine performs a long computational task without regular cancellation checks. The coroutine checks isActive only when suspended (suspending). If the task does not suspend (for example, a long loop or mathematical calculations), it will not see the cancellation request.
  • Cancellation exceptions are not handled (for example, CancellationException is not caught). The coroutine may finish, but the parent coroutine or task manager will not be aware of its cancellation, and resources may not be released properly.
  • Use of non-cooperative dispatchers, such as Dispatchers.Unconfined or a thread pool dispatcher that does not support Cooperative Cancellation. Although a CancellationException will still be thrown, behavior can be unpredictable.
  • Using blocking I/O operations without wrapping them in suspending functions (for example, reading from InputStream in a loop without using withContext(Dispatchers.IO) and suspending methods). A blocking operation does not check the coroutine's state and does not throw CancellationException.

For cooperative cancellation, a coroutine should:

  1. Use a dispatcher that supports Cooperative Cancellation (for example, Dispatchers.Default, Dispatchers.IO, Dispatchers.Main).
  2. Regularly check isActive or use suspending functions that do this for it.
  3. Properly handle CancellationException.
Are there cases when we cannot cancel coroutines… - sobes.tech