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 mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay