Home > Blockchain >  println() not printing a toString() version of a Job object and not erroring out, either
println() not printing a toString() version of a Job object and not erroring out, either

Time:12-04

I've been going through a Pluralsight course on coroutines in Kotlin, and got stuck on this little example, where I am trying to print out the job object passed into the coroutine context. My understanding is that, when faced with a complex object type, println() will default to a .toString() method or print some sort of an object reference. But what's going on here is that println() isn't printing anything inside of $launchParent, yet, the code execution never reaches println("exiting try block"). I've added a try..catch block, thinking there was an exception, but there wasn't. It's just that nothing gets printed after running that offending println() with the $launchParent in it.I am relatively new to Kotlin and feeling a bit mystified by this. I rebuilt the solution, invalidated the cache and restarted, but it didn't help. Any ideas why the println() with the $launchParent string substitution is bombing like this?

import kotlinx.coroutines.*

fun main(args: Array<String>) = runBlocking() {

    println("inside main function within JobsAndChildren module")

    val launchParent: Job = Job()
    val scope = CoroutineScope(Job())

    val job = scope.launch(launchParent) {
        println("Inside the CoroutineScope launch block")
        val j1 = coroutineContext[Job]
        println("after accessing the job key in the coroutineContext array")
        try {
            println("inside the try block")
            println("job passed to the scope.launch as the new context: $launchParent")
            //println("job returned from scope.launch as the new job: $j1")
            println("exiting try block")
        } catch (e: Exception) {
            println("inside the catch block")
            println(e.message)
        }
    }
}

CodePudding user response:

runBlocking and main finish execution before scope.launch does, because scope.launch coroutine is not a child of the runBlocking CoroutineScope. Add job.join()

  • Related