Hello again, why does ```fun businessLogic(...) =...
# coroutines
h
Hello again, why does
Copy code
fun businessLogic(...) = runBlocking(Dispatchers.Default) {
    val businessValue = async { someFunction() }
    ...
}
work but
Copy code
suspended fun businessLogic(...): ReturnValue {
    val businessValue = async { someFunction() }
    ...
}
doesn't? Doesn't the context from wherever this function is called carry over to allow for the async job to be launched?
s
To launch coroutines inside a suspending function you can use a
coroutineScope
block:
Copy code
suspend fun businessLogic(…): ReturnValue {
  coroutineScope {
    val businessValue = async { someFunction() }
    …
  }
}
The
runBlocking
function implicitly creates a coroutine scope for its body code block, for convenience, which is why you don't need to do the same thing there.
gratitude thank you 1
h
Thanks 🙂 feels like something that should happen by default. I guess the idea here would be that whatever code that runs within a suspending function should, ideally, yield when not in use?
s
I think it's good for it to be explicit. The coroutineScope function will wait for all its coroutines to finish, which is important. If you could just call launch/async without it, it would be unclear if the containing function was going to wait for the new task or not.
h
Clear. Feels like making all my functions be
Copy code
suspend fun businessLogic(…) = coroutineScope {
    val businessValue = async { someFunction() }
    …
}
Make sense if that's the case 😅
I'll likely add it wherever I might need to do these async jobs. Thanks!