ardlema
ardlema

Reputation: 85

Play framework - Using WS API

I have to call an external REST service from my Scala Play framework app. Using the WS API I am getting a Future and not sure which is the best way to "extract" the value from this Future. Here is my code:

val externalRestServiceCall: Future[List[Data]] = WS.clientUrl(dataSourceProperties.url).get().map {
  response => response.json.as[List[Data]]
}

And this is my current approach, returning a Future though:

val timeoutFuture = play.api.libs.concurrent.Promise.timeout("Oops", 1 second)
Future.firstCompletedOf(Seq(externalRestServiceCall, timeoutFuture)).map {
  case first: List[Data] => Some(first)
  case _ => None
}

Upvotes: 0

Views: 254

Answers (1)

cchantep
cchantep

Reputation: 9168

In my mind, it's better not to think in 'extracting' future.

If you're in an action, just use Action.async(theWsFuture.map(wsRes => aPlayResult)).

You can also mix 'non-future' result with this future inside .async(...):

def myAction = Action async {
  for {
    a <- Future.successful(syncVal)
    b <- myFuture
  } yield Ok(somethingWithAB)
}

See action composition with future at Play: How to implement action composition .

Upvotes: 1

Related Questions