ListenableFuture to scala Future

后端 未结 2 500
暗喜
暗喜 2021-02-02 08:34

I am in the process of writing a small scala wrapper around a java library.

The java library has an object QueryExecutor exposing 2 methods:

  • execute(query)
2条回答
  •  故里飘歌
    2021-02-02 09:13

    The second option is best, it keeps everything asynchronous. but... you can do one better and abstract the solution into a reusable pattern:

    implicit class RichListenableFuture[T](lf: ListenableFuture[T]) {
      def asScala: Future[T] = {
        val p = Promise[T]()
        Futures.addCallback(lf, new FutureCallback[T] {
          def onFailure(t: Throwable): Unit = p failure t
          def onSuccess(result: T): Unit    = p success result
        })
        p.future
      }    
    }
    

    You can then simply call:

    executor.asyncExecute(query).asScala
    

提交回复
热议问题