curiousengineer
curiousengineer

Reputation: 2625

Better way to return a Future with async going on too

def fun = {
  val a = Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5}
  a onComplete {_ => Thread.sleep(5000); println("Inside map") }
  a
}

Above is a very simple snippet. The return type is Future. Is there a better way without storing the value of Future in a val and still have onComplete but still be able to return the Future?

Upvotes: 4

Views: 78

Answers (2)

Hosam Aly
Hosam Aly

Reputation: 42464

andThen is there to help with side effects. Note that the value that is returned inside the call to andThen is ignored, even if an exception is thrown.

def fun = {
  Future {println("Inside Future"); throw new Exception("Discomfort in the sea has pulled itself upon me"); 5}
    .andThen {case _ => Thread.sleep(5000); println("Inside map") }
}

Upvotes: 3

nmat
nmat

Reputation: 7591

onComplete returns unit so if you specifically want to use onComplete you need the temporary variable. Alternatively, with Scala 2.12, you can use transform to do something similar. Note that you always need the return value:

  def fun = {
    Future {
      println("Inside Future")
      throw new Exception("Discomfort in the sea has pulled itself upon me")
      5
    }.transform {
      res =>
        Thread.sleep(5000)
        println("Inside map")
        res
    }
  }

An alternative for any Scala version is to just do both map and recover with the same body, but it wouldn't be as elegant.

Upvotes: 2

Related Questions