I am using FUTURE in scala on play framework. But I have difficulty to get part of the final result in case of timeout when merging multiple futures. Here is what my code does. It has two future to query two providers respectively. And then use a for/yield statement to merge the results. And then await for the result with a time out value. It works fine when two providers reply to the query on time. However, if just one provider reply on time, I know the await will timeout but in this case I still need to retrieve the data returned from the other provider which replied on time. How do I do that?
val pool = Executors.newCachedThreadPool()
implicit val ec = ExecutionContext.fromExecutorService(pool)
var future1 = Future(QueryProvider(provider1, request1))
var future2 = Future(QueryProvider(provider2, request2))
val future = for {
result1 <- future1
result2 <- future2
} yield (Merge(result1, result2))
val duration = Duration(60000, MILLISECONDS)
try{
result = Await.result(future, duration).asInstanceOf[string]
}
catch{
case _: Exception => println("time out...")
//Here how can I retrieve provider1's result if only provider2 timeout???***
}
You could use
after
fromakka
instead of blockingAwait.result
:In this case
resFuture
will be completed in 60 seconds and you can process partial result. Also you don't needAwait
inPlay
- you could useAsync
.In case you have many equivalent futures of the same type you could use it like this:
Types here are only for illustration.