I have a function that should do its work but also trigger a background process. The triggered process, even though launched within the function, should not hold it from returning because it is not directly related to the work being done.
Code example:
suspend fun coroutiny(): String {
coroutineScope {
launch(Dispatchers.IO) {
delay(1000)
println("Independent thing that should not avoid coroutiny to return")
}
}
return "Coroutiny return"
}
suspend fun main() {
println(coroutiny())
println("after coroutiny")
delay(2000)
}
My Desired result in this situation would be:
Coroutiny return
after coroutiny
Independent thing that should not avoid coroutiny to return
But what I get is:
Independent thing that should not avoid coroutiny to return
Coroutiny return
after coroutiny
I know this happens because coroutineScope {...} only returns when the coroutines inside return/complete. What I need help with is to know how to do what I want without resorting to GlobalScope.launch {...}, which I wanted to avoid as my use case does not match the documented acceptable use cases for GlobalScope.