The best way to bring the future back with asynchronous motion

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. Return type Future. Is there a better way without saving the value Futurein valand still have onComplete, but still be able to return Future?

+4
source share
2 answers

onCompletereturns a block, so if you specifically want to use onComplete, you need a temporary variable. Alternatively, with Scala 2.12, you can use the transform to do something like this. Note that you always need to return a 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 version of Scala is to simply make both a map and restore with the same body, but that would not be so elegant.

+2

andThen, . , , andThen, , .

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") }
}
+2

Source: https://habr.com/ru/post/1694365/