At several points of my program, I use launch
to start a coroutine that does some background tasks. Then, at some point, I return from the main
function. A simplified version of my program could look like this:
fun main(args : Array<String>)
{
launch {
delay(10000) // some long running operation
println("finished")
}
}
Now, the coroutine starts as expected and starts running the operation - and then the program exits. If I don't return from main
or replace launch
with thread
, everything works as expected. So how can I, given that I don't keep track of all coroutines started in my program (hence I cannot use .join()
or .await()
), make sure that all coroutines finish before my program exits?
So how can I, given that I don't keep track of all coroutines started in my program (hence I cannot use .join() or .await()), make sure that all coroutines finish before my program exits?
You need to keep track and await the results at some point in order to be sure that those coroutines have finished. That’s because “coroutines are like daemon threads”:
Active coroutines do not keep the process alive. They are like daemon threads.
This is not the case for regular Java Thread
s which are non-daemon by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With