Pergunta

I have two webservice calls. Webservice1 returns Promise[Option[Model]] and Webservice2 should take Model as a parameter and then return a Promise[Option[String]]. This is how I have structured my code:

  def call1: Promise[Option[Model]] = for {
    response1 <- callService1(requestHolderForService1)
  } yield {
    for {
      response <- response1
    } yield ParserForResponse(response)
  }

After, this I want to chain my call to service 2 that takes the result from service 1 as a parameter:

   def call2:Promise[Option[String]] = call1.flatMap{
    optionModel => optionModel.flatMap{
      model => callService2(requestHolderForService2(model)).map{
        service2Option => service2Option.map{
          service2Result => ResultParse(service2Result)
        }
      }
    }
  }

The problem is that my call1 returns a Promise[Option[Model]] whereas the return from call2 needs to be Promise[Option[String]]. The issue stems from the intermediate service call

callService2

which returns Promise[Option[JsValue]] and I am unable to figure out the transition from Promise[Option[Model]] -> Promise[Option[JsValue]] -> Promise[Option[String]]

Can somebody point out how I might be able to chain these two calls together using map or flatMap?

Thanks

Foi útil?

Solução

The "normal" way would not to be working with the promises directly, but futures for those promises, which you can access from scala.concurrent.Promise.future

First you map the future, think of it as when the option arrives, do this transformation with it, then you need to handle the fact that the option may not exist, which also is a map, think of it as if there is a value to this tranformation on it.

so:

val future1: Future[Option[Model]] = (...).future
val future2: Future[Option[String]] = future1.map { maybeModel => 
  maybeModel.map(model => model.toString) // or hovewer you make it a string
}

Which you then can use in your second web service call

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top