Reputation: 7053
Can someone enlighten me about what is going on in this code example:
import kotlinx.coroutines.*
import kotlin.time.*
fun subTask(scope: CoroutineScope): Job {
val job = scope.launch(Dispatchers.IO){
println("SubTask started.")
delay(500L)
println("SubTask ending.")
}
job.invokeOnCompletion(object: CompletionHandler{
override fun invoke(cause: Throwable?) {
println("SubTask completed.")
}
})
return job
}
fun main() {
val duration = measureTime {
runBlocking {
val job = withContext(Dispatchers.IO) {
subTask(this)
}
println("Waiting for SubTask")
job.join()
}
}
println("Duration: $duration")
}
(Click here for Kotlin playground)
I was expecting to see
SubTask started.
Waiting for SubTask
SubTask ending.
SubTask completed.
Duration: 600ms
But I am getting
SubTask started.
SubTask ending.
SubTask completed.
Waiting for SubTask
Duration: 600ms
Why isn't the subTask run in parallel with main()?
Upvotes: 1
Views: 1930
Reputation: 93639
withContext
suspends until it is complete. Since you are passing the scope of the withContext
to subTask()
and subTask()
uses it to launch its job, withContext
will suspend until this other launched job completes. If subTask()
used a different CoroutineScope
, or if you had not wrapped your subTask()
call in withContext
, you would have had your expected behavior.
Upvotes: 3