[SOLVED] CompletableFuture equivalent in Scala


#1

How can I achieve the same effect described below in a non-blocking way (Scala style) not using CompletableFuture, function converter from Java to Scala, Akka or Actor that kind of thing?

Thanks


#2

Come across to the doc - https://docs.scala-lang.org/overviews/core/futures.html

Testing with following code that seems to achieve the effect I need, but not sure if this is correct or not.

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Failure
import scala.util.Success

object MyTest {

  @throws(classOf[Exception])
  def main(args: Array[String]) {
        val f = Future[String] { 
        println(s" ${Thread.currentThread.getName} Simulate heavy working ...")
        Thread.sleep(5 * 1000)
        "hey, sub task is done!" 
    }
    f.onComplete {
        case Success(result) => notify(result)
        case Failure(ex) => println(s"Oh, no!!!! bad thing happends $ex")
    }
    println(s"At the same time '${Thread.currentThread.getName}' doing the main task ...")
    Thread.sleep(1000 * 10)
    println(s"Task done by '${Thread.currentThread.getName}'!")
  }

  def notify(result: String) {
      println(s"${Thread.currentThread.getName} calls notify() method! Result is $result ...")
  }
}

#3

future.onComplete


#4

Looks fine.


#5

Thanks. I’ll mark this as solved.


#6
for (result <- f) notify(result)

would also work (but be silent on errors).