https://kotlinlang.org logo
Title
r

Ryan Zidago

01/14/2022, 5:46 PM
How can I make a coroutine print to another one? If I do:
fun someFunction() = runBlocking {
  greet()
}

suspend fun greet() = coroutineScope {
  launch {
    delay(1_000)
    println("world!")
  }
  println("hello")
}
I will see both "hello" and "world!" printed, but the code is blocked until
greet
is done. However if Iaunch
greet
inside a coroutine:
fun someFunction() = runBlocking {
  launch {
    greet()
  }
}

suspend fun greet() = coroutineScope {
  launch {
    delay(1_000)
    println("world!")
  }
  println("hello")
}
the code is non blocking anymore but I can't see any messages printed to the console 🤔
j

Joffrey

01/14/2022, 5:52 PM
Which version of coroutines are you using? The standalone
launch
in your
greet()
function should not compile without coroutine scope 🤔
r

Ryan Zidago

01/14/2022, 6:03 PM
My bad I forgot to add the
coroutine
scope. I just edited my post.
j

Joffrey

01/14/2022, 6:13 PM
That edited code works fine, and prints stuff. They are both equivalent because
runBlocking
waits for child coroutines to finish before returning. You can see it run here: https://pl.kotl.in/DHI3W7ifV If you're not seeing this result, you should probably share the actual code you're using
r

Ryan Zidago

01/14/2022, 6:25 PM
Here's what I have: https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS42LjEwIiwiY29kZSI6InBhY2thZ2UgY29tLnJ5YW[…]hcIkhlbGxvXCIpXG59IiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiJ9 Sorry for the messy code; but I'm building a GraphQL server with Ktor and KgraphQL. When a user creates a mutation, I want to have a coroutine print a message to the console after a certain time, let's say 1 minute, without blocking the execution of the code. When I run the code above, I cannot see anything printed to the console.
I've finally found the solution: After having read this article, I've noticed that I needed to use the
IO Dispatcher
. So the dummy code would look like this.