DEV Community

Emily Johnson
Emily Johnson

Posted on

Master Canceling: 5 Proven Ways to Abort Coroutines Fast

At some point, you'll face a situation where you need to halt a coroutine that's already underway. Let's explore the process of doing so.

Terminating a Job

A job has several functions at its disposal, including cancel, which appears to be the ideal solution. Moreover, we can utilize join to wait until the job has completed its termination.

The example below demonstrates a job being terminated:

runBlocking {
  val job = launch(Dispatchers.Default) {
    for (i in 0..1000) {
      delay(50)
      println("$i..")
    }
    println("Job is completed")
  }
  delay(500)
  println("Terminating")
  job.cancel()
  job.join()
  println("Terminated and done")
}

The output will be:

0..
1..
2..
3..
4..
5..
6..
7..
8..
Terminating
Terminated and done

For more information on canceling Kotlin coroutines like a pro, check out this article: 5 Essential Techniques.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay