Hi, what is the right way to kick off an async tas...
# coroutines
e
Hi, what is the right way to kick off an async task but then immediately return with the result of my original operation?
Copy code
suspend fun callback() { ... }

suspend fun execute(request: Request): Response {
    val response = ... 

    callback()
    
    return response
}
I mean, is it just as simple as this sample above?
s
No, this does not return immediately. Instead, you may want to change your execute function.
Copy code
fun CoroutineScope.execute(request: Request, callback: suspend () -> Unit) {
  val response: Response = ...
  launch { callback() }
  return response
}
e
thanks!
fwiw the syntax above causes warningns in ide, so instead, it’s something like:
Copy code
suspend fun execute(request: Request, callback: suspend () -> Unit): Response = withContext(Dispatchers.Default) {
   val response : Response = ...
   launch { callback() }
   response
}
how can I write a unit test that verifies the execution order?
n
What you wrote is the same as if you didn't launch at all and just called callback directly (guessing you just missed suspend at beginning or it won't compile).
withContext
will wait for all child coroutines to finish (read up on structured concurrency for why). In general it's not a great idea to have a suspend function that returns before it's finished all the work it started. Usually a method is either suspend or it takes a CoroutineScope somehow, usually not both. What warnings in ide did you get? Is the
...
stuff suspending code?
See https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/ for help testing coroutines. In general you can't test order when launching because launching doesn't really guarantee order. It may run immediately, or later, or at the same time. If you care about order then you need to force things to run in the order you want. If you just want to test "it doesn't wait" then you can give a callback that waits for a signal (like
val job = Job(); job.join()
) and check that the other function returns without giving the signal (
job.complete()
).
e
thanks for the feedback, will rethink this again