title: How To Stop Or Cancel A Kotlin Coroutine (Stop Currently Running Code Block Instantly)?
body: <p><strong>What I want to achieve?</strong></p>
  <p>I have a task to download images but as the screen scrolls it will cancel previous downloads and start downloading new ones. I want that when it cancel the <code>coroutine</code> downloading previous image it stop instantly and free up the <code>bandwidth</code> so new images download faster.</p>
  <p><strong>What I have tried?</strong></p>
  <p>I have tried multiple ways to stop the <code>coroutine</code> but it keeps going until it finishes the downloading even after cancelling the <code>coroutine</code>. When I cancel the <code>coroutine</code> it makes a variable <code>isActive</code> to <code>false</code> and stop calling further suspended function. But the problem is if its running a <code>loop</code> for <code>1000000</code> times or downloading an image from <code>network</code> this task will not canceled unless completed. Like loop will complete it's <code>1000000</code> iterations then the coroutine will be cancelled.</p>
  <p>I have tried these but no success:</p>
  <pre><code>job.cancel()
  scope.cancel()
  </code></pre>
  <p>I have tried so many ways for achieving this but got no solution. I can't use any library right now in my project.</p>
  <p><em><strong>This use case not achieved by Threads, Executor Service, Coroutines. Because all behave the same.</strong></em></p>
  <p>More questions same like this :</p>
  <p><a href="https://stackoverflow.com/questions/67069391/how-do-i-cancel-a-kotlin-coroutine-for-a-blocking-download-operation?rq=1">How do I cancel a kotlin coroutine for a blocking download operation</a></p>
  <p><a href="https://stackoverflow.com/questions/14724640/asynctask-is-not-cancelling-the-long-running-operation-in-android?rq=1">AsyncTask is not cancelling the long running operation in android</a></p>
  <p><a href="https://stackoverflow.com/questions/68080753/leaking-service-held-by-coroutine">Leaking Service held by Coroutine</a></p>