future

ListenableFuture to scala Future

断了今生、忘了曾经 提交于 2019-12-03 08:17:38
问题 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): Result asyncExecute(query): ListenableFuture[Result] ListenableFuture in this context is the one from the guava library. I want my scala wrapper to return a Future[Result] instead of the java object, but I am not sure what is the best way to implement that. Here are 2 solutions I came up with: future { executor.execute(query) } and val p

How to use ExecutorService to poll until a result arrives

送分小仙女□ 提交于 2019-12-03 07:48:27
I have a scenario where I have to poll a remote server checking if a task has completed. Once it has, I make a different call to retrieve the result. I originally figured I should use a SingleThreadScheduledExecutor with scheduleWithFixedDelay for polling: ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture future = executor.scheduleWithFixedDelay(() -> poll(jobId), 0, 10, TimeUnit.SECONDS); public void poll(String jobId) { boolean jobDone = remoteServer.isJobDone(jobId); if (jobDone) { retrieveJobResult(jobId); } } But since I can only provide a

How to resolve a list of futures in Scala

情到浓时终转凉″ 提交于 2019-12-03 06:50:14
问题 I have a call that returns a Future. However, I need to make n calls so I will get back n futures. I am wondering how I would get the futures to all resolve before proceeding (without blocking the server) For example, while(counter < numCalls){ val future = call(counter) future.map{ x => //do stuff } counter += 1 } //Now I want to execute code here after ALL the futures are resolved without //blocking the server 回答1: You can use Future.sequence(futureList) to convert a List[Future[X]] to a

Futures in Haskell

余生颓废 提交于 2019-12-03 06:42:13
Does Haskell have an equivalent of Alice's ability to bind a variable to a future? val a = spawn foo; where foo is some function. I know Haskell supports channels and threads; I'm hoping for syntax as natural as Alice's to bind a value to a future and spawn a thread to calculate it without having to deal with the details. You can use par from Control.Parallel as in a `par` f a b c where a = foo This is a hint to the runtime that a could be evaluated in another thread. Funny, I was just reading a new post by Simon Marlow: Parallel programming in Haskell with explicit futures . Apparently he and

How are Scala Futures chained together with flatMap?

眉间皱痕 提交于 2019-12-03 06:36:42
I'm working on using Futures for the first time in Scala and am working through an example of using the flatMap combinator; I've been following this discussion: http://docs.scala-lang.org/overviews/core/futures.html Specifically, this example: val usdQuote = future { connection.getCurrentValue(USD) } val chfQuote = future { connection.getCurrentValue(CHF) } val purchase = for { usd <- usdQuote chf <- chfQuote if isProfitable(usd, chf) } yield connection.buy(amount, chf) purchase onSuccess { case _ => println("Purchased " + amount + " CHF") } is translated to this: val purchase = usdQuote

Map the Exception of a failed Future

☆樱花仙子☆ 提交于 2019-12-03 06:34:37
问题 What's the cleanest way to map the Exception of a failed Future in scala? Say I have: import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global val f = Future { if(math.random < 0.5) 1 else throw new Exception("Oh no") } If the Future succeeds with 1 , I'd like to keep that, however if it fails I would like to change the Exception to a different Exception . The best I could come up with is transform, however that requires me to make a needless function for the

Waiting for callback for multiple futures

柔情痞子 提交于 2019-12-03 06:27:11
Recently I've delved into a little bit of work using an API. The API uses the Unirest http library to simplify the work of receiving from the web. Naturally, since the data is called from the API server, I tried to be efficient by using asynchronous calls to the API. My idea is structured as follows: Create array of data by returning the results of futures Display data + additional information gathered from the data Therefore, I need to have all the data returned before I can start the second step. My code is as follows: Future < HttpResponse < JsonNode > > future1 = Unirest.get("https:/

Why does the andThen of Future not chain the result?

泄露秘密 提交于 2019-12-03 05:41:50
The andThen meaning I learned from this answer is a function composer. Say that f andThen g andThen h will equal to h(g(f(x))) This implies the h function will receive input from g(f(x)) But for the andThen in Future , all the closure of the following andThen always receives the result from the original Future . Future{ 1 }.andThen{ case Success(x) => println(x) // print 1 Thread.sleep(2000) x * 2 }.andThen{ case Success(x) => println(x) // print 1 Thread.sleep(2000) x * 2 } compare to val func: Function1[Int, Int] = { x: Int => x }.andThen { y => println(y) // print 1 y * 2 }.andThen { z =>

Play 2.2 -Scala - How to chain Futures in Controller Action

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 04:42:22
I have 3 futures of type Response. The first future returns a JsValue which defines if future 2 and future 3 shall be executed or only future 3 shall be executed. Pseudocode: If Future 1 then {future2 and future 3} else future 3 Iam trying to do this in a play framwork action which means in order to use the result of the futures later I cant use onSuccess, onFailure and onComplete because all of them return Unit and not the actual JsValue from the last future. I tried to do this with map() and andThen but I am a Scala noob and I guess i wasn't able to do it because I always just missed a

Scala Option[Future[T]] to Future[Option[T]]

断了今生、忘了曾经 提交于 2019-12-03 04:40:46
How can I convert Option[Future[T]] to Future[Option[T]] in scala? I want to use it in: val customerAddresses = for { a <- addressDAO.insert(ca.address) // Future[Address] ia <- ca.invoiceAddress.map(addressDAO.insert) // Option[Future[Address]] } yield (a, ia) // Invalid value have to be two futures Here signature insert method def insert(address: Address): Future[Address] ca is a CustomerData case class CustomerData(address: Address, invoiceAddress: Option[Address]) import scala.concurrent.Future import scala.concurrent.ExecutionContext def f[A](x: Option[Future[A]])(implicit ec: