How can I structure onComplete in Scala to act in this way:
Fig. 1
{
var x;
if(result.isFailure){
x = foo() // foo is a future
}
if(result.isSuccess){
x = 5
}
bar(x)
}
I thought I could do it this way:
Fig. 2
var x = foo onComplete {
case Success(x) => 5
case Failure(t) => foo() //foo is a future
}
bar(x)
But onComplete, onFailure and onSuccess all have Unit
as their return type,
onComplete[U](f: (Try[T]) ⇒ U)(implicit executor: ExecutionContext): Unit
onSuccess[U](pf: PartialFunction[T, U])(implicit executor: ExecutionContext): Unit
onFailure[U](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Unit
How can I achieve something figure two-ish without using a var?
It is discouraged to block current thread by awaiting a result from a future. Instead, you should call bar() function on processing results of the result
future.
result map {r =>
5
} recover {
case _ => foo()
} map {r =>
bar(r)
}
You can achieve your goal with
val x: Future[Int] = foo.map(x => 5).recover{case f => foo()}
// do some more work with your future
x.map(bar(_))
Assuming that foo: Future[_]
and foo(): Int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With