Panda World
Panda World

Reputation: 1996

Coroutine combined Job is not completed

When getting a job from launch, the job complete properly

fun testCoroutineScope() = runBlocking {
    val scope = CoroutineScope(Dispatchers.Default)
    val job = scope.launch {
        delay(200)
        println("Job done")
    }
    delay(500)
    println(job.isCompleted)
}

Output:

Job done
true

But this is not the case when you combine your own job.

fun testCoroutineScope() = runBlocking {
        var job = Job()
        val scope = CoroutineScope(Dispatchers.Default + job)
        scope.launch {
            delay(200)
            println("Job done")
        }
        delay(500)
        println(job.isCompleted)
}

Output:

Job done
false

Looks like the job is never completed. Why is that?

Upvotes: 2

Views: 536

Answers (1)

Tenfour04
Tenfour04

Reputation: 93659

scope.launch creates a new Job. When you do Dispatchers.Default + job, you are not passing your job to the scope. You are creating a new CoroutineContext that combines elements of the job and Dispatchers.Default. The literal job object itself is not passed to the new context.

Upvotes: 3

Related Questions