How to repeat the request on Play! structure 2.1?

Is there an easy way to repeat the request until I get a success result in Play2.1 (scala)? And how to limit the number of attempts?

I want to do something like this:

WS.url("some.url").get().map{ response => val strval = someFunction(response) strval match { case "success" => println("do something after successful request") case "error" => println("repeat same request until success - and repeat maximum N times!") } } 

Thanks in advance!

+4
source share
2 answers

Not verified

You can do something like this:

 import scala.concurrent._ import play.api.libs.concurrent.Execution.Implicits._ def withRetry[T](retries:Int = 5)(f: => Future[T]) = f.recoverWith { case t:Throwable if (retries > 0) => withRetry(retries - 1)(f) } 

And then in your own code, you can use it like this:

 withRetry(retries = 2) { WS.url("some.url").get .map { response => require(someFunction(response) != "error", "Please retry") response } } 

If you want to rewrite someFunction to Response => Boolean , you can use it like this:

 def someFunction(r: Response): Boolean = ??? withRetry(retries = 2) { WS.url("some.url").get .filter(someFunction) } 
+3
source

Try the following:

 def wSCall = WS.url("http://foo/bar").get() def ƒ(response: Response, n: Int): Result = { val strval = someFunction(response) strval match { case "success" => Ok("Ok!") case "error" => { if (n > 0) Async { wSCall.map(response => ƒ(response, n - 1)) } else BadRequest("Fail :(") } } } Async { wSCall.map(response => ƒ(response, 10)) } 
+2
source

All Articles