I am not an expert in Scala and this might be trivial scenario, tried a lot but it doesn't seem to work.
Basically based on a condition I need to call an api and based on the response of the api I need to call another api
def getVal (o: String, site: Option[String]): Future[T] {
val sp = site match {
case some(s) => apiCall1(s) // The response here is Future[Option[T]]
case _ => None // What should be here is also a question
}
sp match { // I think the issue is this match
case some(sp1) => {
//flow never comes here
sp1.asInstanceOf(Future[T])
}
case _ => apiCall2(o) // The response here is Future[T]
}
}
The response of above method is always what apiCall2 returns. I kept debug statements and I can see sp1 has a value for Future[Success[Some[T]]].
As I don't know the behavior of the underlying APIs, I mocked the underlying APIs like this:
def apiCall1(string: String): Future[Option[String]] = {
if (string == "") Future(None) else Future(Some(s"Response 1: $string"))
}
def apiCall2(string: String): Future[String] = {
Future(s"Response 2: $string")
}
The final result will depend on the behavior of the underlying APIs, but this implementation will cover all cases.
You should implement the getVal
function like this to use the result of the first API properly:
def getVal(o: String, site: Option[String]): Future[String] = {
val sp = site match {
case Some(s) => apiCall1(s)
case _ => Future.successful(None)
}
sp.flatMap {
case Some(spValue) => Future(spValue)
case _ => apiCall2(o)
}
}
Now, if you run these functions with these inputs:
getVal("O", None).onComplete { result => println("O", None, result) }
getVal("O", Some("")).onComplete { result => println("O", Some(""), result) }
getVal("O", Some("Input")).onComplete { result => println("O", Some("Input"), result) }
You will get these outputs:
(O,None,Success(Response 2: O))
(O,Some(),Success(Response 2: O))
(O,Some(Input),Success(Response 1: Input))