Search code examples
javascalalistenerpojo

Scala syntactic sugar with java listener pattern


I have to use java code in my scala project. The java code encourages the usage of a listener pattern. The code is something like this:

 asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(new AsyncCompletionHandler<Response>(){

    @Override
    public Response onCompleted(Response response) throws Exception{
        // Do something with the Response
        // ...
        return response;
    }

    @Override
    public void onThrowable(Throwable t){
        // Something wrong happened.
    }
});

I am wondering if it is possible to use anything better in scala with this code. I know there is a paper written by Martin Odersky saying that observer pattern is bad but I didn't go deep with the matter. Thanks


Solution

  • If you can't change the signature of your execute method, you could write a convenience method to simplify creation of the callback:

    def async(f: Response => Response)(handler: Throwable => Unit) =
       new AsyncCompletionHandler[Response]() {
          @throws(classOf[Exception])
          override def onCompleted(response: Response): Response = 
             f(response)
    
          override def onThrowable(t: Throwable) = handler(t)
       }
    

    Then you can write your code like

     asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(async {
        response => // do something with response
     } { 
        caught => // handle failure
     }