Suppose you have a list of URLs that you are looking to select:
val urls = List(
"http://www.google.com",
"http://stackoverflow.com",
"http://www.bing.com"
)
In Play 2.5.x, we can process them sequentially and use them akka.pattern.afterto force an asynchronous delay between each call. We are the flatMapresult of Futurea webservice request that it will return the same value in one second.
Future.traverse(urls) { url =>
wsClient.url(url).get().flatMap { result =>
akka.pattern.after(1.second, actorSystem.scheduler)(Future.successful(result))
}
}
This requires the presence of WSClientboth a ActorSystemcomponent, as well as an implicit one ExecutionContextin the region.
In Play 2.4.x and earlier, you can do the same with Promise.timeout:
Future.traverse(urls) { url =>
wsClient.url(url).get().flatMap { result =>
Promise.timeout(result, 1.second)
akka.pattern.after(1.second, actorSystem.scheduler)(Future.successful(result))
}
}
source
share