Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala return value from onComplete

Tags:

scala

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?

like image 400
krzasteka Avatar asked Sep 01 '15 14:09

krzasteka


2 Answers

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)
}
like image 105
Alexander Tokarev Avatar answered Oct 29 '22 10:10

Alexander Tokarev


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.

like image 6
Till Rohrmann Avatar answered Oct 29 '22 11:10

Till Rohrmann