Nidhin S G
Nidhin S G

Reputation: 1695

Dealing with Multiple Api Calls and Global Variables in Play Scala

I am trying to call 2 apis in a single method and I have to do a few calculations based on the responses I get.

This is so far what I have tried

def sortedRes() = Action.async {
    ws.url(url).get().map { response =>
      val value: JsValue = Json.parse(response.body)
      val headVal = value.get.head
      ws.url(sortUrl).get().map { response =>
        val sorted: JsValue = Json.parse(response.body)
        var sortedResult = sorted.get.head
      }
      println("----------------------")
      println(headVal)
      println(sortedResult)
      Ok(Json.toJson(sortedResult)
    }
  }

I am getting an error on println(sortedResult) line as it is not available there. How can I access sortedResult there in scala.

Upvotes: 0

Views: 240

Answers (2)

o-0
o-0

Reputation: 1789

Couple of things about your written code:

  1. Use Flatmap on outer Future calls: You have asynchronous action, every ws call type should have the Future type and therefore the outer map should be flatMap for avoiding dealing with Future[Future[...]].

  2. Don't use var: The whole point of functional programming is immutability use val instead. If you can' think about your architecture/design and re implement the written function.

  3. Move the action response to the body of Map: For more clean approach, why not move the Ok response to the body of the second map?

Upvotes: 1

Luca T.
Luca T.

Reputation: 1651

As the ws.url(whatever).get() is asynchronous, it will return a Future that will contain your response, so it's not available in the moment you want to print it.

You have to flatMap the outer Future in order to manage the inner one, so then your sortedResult will be available

I think this is what you want to do:

def sortedRes() = Action.async {
  ws.url(url).get().flatMap { response =>
    val value: JsValue = Json.parse(response.body)
    val headVal = value.get.head
    ws.url(sortUrl).get().map { response =>
      val sorted: JsValue = Json.parse(response.body)
      val sortedResult = sorted.get.head

      println("----------------------")
      println(headVal)
      println(sortedResult)
      Ok(Json.toJson(sortedResult)
    }
  }
}

Upvotes: 1

Related Questions