Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala future return based on first future result

I have a Scala future that calls an api and returns future, if the result isn't correct, then another api call will be submitted with first future's result and returned as future.

This is what I have so far.

val fut1 = Future(queryFirst)
val fut2 = fut1 map {
  case y if y.isInstanceOf[NoResult] => Future(queryAgainWithFut1Result)
  case x => x
}

But if I access fut2 result, it gives something like this:

scala.concurrent.Await.result(fut2, 5 seconds)
warning: there was one feature warning; re-run with -feature for details
fut2: Any = scala.concurrent.impl.Promise$DefaultPromise@61ab71c2

Is there a way that I can choose to return fut2 if fut1 result is not accurate?

Edit: Second future has to use first future to continue api call. This is what I have so far.

val fut1 = Future("queryFirst")
val fut2 = fut1 flatMap {
  case y if y.isInstanceOf[Int] => Future("queryAgainWithResult(y)")
  case x => Future(x)
}
like image 936
angelokh Avatar asked Feb 10 '23 16:02

angelokh


1 Answers

You can filter the first Future to cause it to fail when its contained result doesn't match what you want, then use recoverWith to recover the value to another Future.

Future(queryFirst)
    .filter(result => /* logic that returns true if result is correct */)
    .recoverWith { case NonFatal(e) => Future(querySecond) }

If queryFirst is successful and makes it through the filter, then it's result will be returned (wrapped in the Future).

If queryFirst is successful and does not have a correct value according to the filter or simply fails, then the result of Future(querySecond) will be returned, success or fail.


Edit: In light of the new information from the OP, if you need the result of the incorrect first Future, then you don't really have a choice but to use flatMap.

Future(queryFirst).flatMap {
    case result if(/* failed condition */) => Future(querySecond(result))
    case result => Future.successful(result)
}
like image 185
Michael Zajac Avatar answered Feb 16 '23 02:02

Michael Zajac