Skip to content

Instantly share code, notes, and snippets.

@zontyp
Created April 14, 2025 13:08
Show Gist options
  • Select an option

  • Save zontyp/d85913434bde84f926fa098b8b788dc5 to your computer and use it in GitHub Desktop.

Select an option

Save zontyp/d85913434bde84f926fa098b8b788dc5 to your computer and use it in GitHub Desktop.

Revisions

  1. zontyp created this gist Apr 14, 2025.
    19 changes: 19 additions & 0 deletions CoroutineCancelGoto.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    import kotlinx.coroutines.*
    fun main() = runBlocking {
    val job = launch {
    try {
    repeat(1000) { i ->
    println("Job: I'm working $i...")
    delay(500L)
    println("at end of try")
    }
    } finally {
    println("Job: I'm running cleanup tasks")
    }
    }
    delay(1300L) // Let the coroutine work for a while
    println("Main: I'm tired of waiting!")
    job.cancel() // Cancels the job
    job.join() // Waits for job's completion
    println("Main: Now I can quit.")
    }