https://kotlinlang.org logo
#ktor
Title
# ktor
s

Sean Abbott

06/24/2021, 6:28 PM
What's the best way to use coroutines to launch work and then respond without waiting for the work to finish? Basically, I want to accept a request, validate it, launch work, and then respond that it was a valid request and work is being done. I don't need to have a callback for this. So like (pseodo-kotlin-ish)
Copy code
route("/foo") {
  get("{bar}") {
    if not validFoo(call.parameters) return@get call.respondText("invalid", status = HttpStatusCode.BadRequest)
    launch { longRunningWorkIDontNeedAResponseFrom(call.parameters) }
    call.respondText("Started work")
  }
}
I know I'm using coroutine already, but...do I need to set up the coroutine scope? Can I share a thread pool with ktor?
I've seen this example https://github.com/ktorio/ktor-samples/blob/1.3.0/feature/async/src/AsyncApplication.kt But that example waits for the results, which I don't want to do .
I can just use launch as long I'm calling suspended functions.
b

Brad Murray

06/24/2021, 8:21 PM
the request handler already has a coroutine scope, but for long-running work you might want to launch on Dispatchers.IO. Another common pattern is to have the call to a service synchronously return a reference to the work that also gets launched, so that you can eventually provide some form of UX where the client gets notified the work is complete.
s

Sean Abbott

06/24/2021, 8:36 PM
Thank you! I'll launch on dispatchers, I expect. We don't need the callback references though; nature of the work.