Search code examples
kotlinkotlinx.coroutines

Coroutine job never completing


Given this piece of code


fun main() {
    val job = Job()
    val scope = GlobalScope + job

    scope.launch {
        println("working!")
        delay(1000L)is ms)
        println("done!")
        // how do i finish the job originally associated with this scope?
    }


    runBlocking {
        job.join()
        println("job done")
    }
}

I have a custom coroutine scope for my application, and i'm associating a job with this scope like that, reason being i want all the new coroutines that are created from this scope to be the children of this job, if i cancel it i want everything in it to be cancelled.

But main job itself is never completing. How do i complete the main job when the task is done? or failed...


Solution

  • Let's simplify your code to something like this:

    val job = Job()
    runBlocking {
        job.join()
    }
    

    If you run this code you will see that it also never completes. That is because job.join() suspends until the given job reaches a terminal state which is either completed or canceled (see docs).

    When you create a job using some coroutine builder (like .launch {...}) you do not need to complete it by yourself. But since you have created it using a factory method Job() it is now your responsibility to complete it.

    You can also find more detailed explanation here.