I am going to use Dispatch to write a simple HTTP client. I call dispatch.Http
to get a future and call the future to get the response
val request = ... val future = Http(request) // call the server asynchronously val response = future() // wait for the response from the server
Now I wonder how I can wait with timeout. I would like the last API call to be:
// throw an exception if no response received within timeout val response = future(timeout: Long)
Does it make sense ?
I understand that Dispatch
return scala.concurrent.Future
, which does not provide API with timeout. How would you suggest me implement it ?
First, you can use Await:
import scala.concurrent.Await
import scala.concurrent.duration._
Await.result(future, 10 seconds) //you can specify timeout here
The problem is that it will throw an exception if the future did not manage to return in specified timeout.
If you need more flexibility here is the second approach:
val futureTimeout = Promise.timeout("Timed out" /* or throw new RuntimeException("timed out") */, 10 seconds)
Future.firstCompletedOf(Seq(futureResult, futureTimeout)).map {
case result: SomeType => //do something
case timedOut: SomeOtherType => //handle timeout
}