ListenableFuture to scala Future

后端 未结 2 384
暗喜
暗喜 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:09

    Another, slightly shorter solution:

    implicit class ListenableFutureDecorator[T](val f: ListenableFuture[T]) extends AnyVal {
      def asScala(implicit e: Executor): Future[T] = {
        val p = Promise[T]()
        f.addListener(() => p.complete(Try(f.get())), e)
        p.future
      }
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题