Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a asynchronous response in an Undertow HttpHandler

I am looking for an example that shows how you write the Response in an undertow HttpHandler asynchronously? The problem is that when HttpServerExchange.endExchange is called the Response is flushed. My sample HttpHandler uses the rx-java library from Scala.

class MyHandler() extends HttpHandler {
  override def handleRequest(exchange: HttpServerExchange) = {
    val observable = Observable.items(List(1, 2, 3)) // simplistic not long running
    observable.map {
      // this is run async
      myList => exchange.getResponseSender.send(myList.toString)
    }
  }
}
like image 946
reikje Avatar asked Aug 08 '14 13:08

reikje


Video Answer


1 Answers

If you call the dispatch() method the exchange will not end when the call stack returns, however even that would be racy in this case.

You probably want something like:

exchange.dispatch(SameThreadExecutor.INSTANCE, () -> {
observable.map {
  // this is run async
  myList => exchange.getResponseSender.send(myList.toString)
}}

Basically this will wait till the call stack returns before running the async task, which means that there is no possibility of a race. Because the exchange is not thread safe this approach makes sure only one thread can run at a time.

like image 196
Stuart Douglas Avatar answered Oct 01 '22 15:10

Stuart Douglas