krzasteka
krzasteka

Reputation: 427

Scala return value from onComplete

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?

Upvotes: 21

Views: 14161

Answers (2)

Till Rohrmann
Till Rohrmann

Reputation: 13346

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.

Upvotes: 6

Alexander Tokarev
Alexander Tokarev

Reputation: 2763

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)
}

Upvotes: 15

Related Questions