Advertisement
Guest User

Untitled

a guest
Apr 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.57 KB | None | 0 0
  1. import scala.concurrent.{Future, Promise}
  2. import scala.util.{Failure, Random, Success}
  3.  
  4. import scala.concurrent.ExecutionContext.Implicits.global
  5.  
  6. object FutureTest {
  7.  
  8.   /** This immitates the BaseRecognizeCallback that you have. */
  9.   trait BaseRecognizeCallback {
  10.     def onTranscription(result: String): Unit
  11.     def onFailure(exception: Throwable): Unit
  12.   }
  13.  
  14.   /**
  15.    * A function that computes the result asynchronously and informs the calling code through
  16.    * a callback. In your case, this would be this 'recognizeUsingWebSocket'.
  17.    * @param callback the function that will be called, when the result is available.
  18.    */
  19.   def recognizeUsingWebSocket(callback: BaseRecognizeCallback): Unit = {
  20.     new Thread(() => {
  21.       val randomSeconds = new Random().nextInt(5)
  22.  
  23.       println(s"Waiting randomly for $randomSeconds seconds")
  24.       Thread.sleep(randomSeconds * 1000L)
  25.  
  26.       if (randomSeconds % 2 == 0) {
  27.         callback.onFailure(new RuntimeException(s"Randomly Failed after $randomSeconds seconds"))
  28.       } else {
  29.         callback.onTranscription("Complete Success!")
  30.       }
  31.     }).start()
  32.   }
  33.  
  34.   def getResultsLater(): Future[String] = {
  35.     val maybeSolution = Promise[String]()
  36.  
  37.     val cb = new BaseRecognizeCallback {
  38.       override def onTranscription(result: String): Unit =
  39.         maybeSolution.complete(Success(result))
  40.  
  41.       override def onFailure(exception: Throwable): Unit =
  42.         maybeSolution.complete(Failure(new RuntimeException("Error while doing complicated work!", exception)))
  43.     }
  44.  
  45.     // now tell our asynchronous computation to compute the result
  46.     recognizeUsingWebSocket(cb)
  47.  
  48.     // return the future result
  49.     maybeSolution.future
  50.   }
  51.  
  52.   /**
  53.    * Just to make the example complete, here's the case where we don't have to wait.
  54.    * @return future results.
  55.    */
  56.   def getImmediateResults(): Future[String] = {
  57.     Future("This was quick!")
  58.   }
  59.  
  60.  
  61.   def main(args: Array[String]): Unit = {
  62.     val laterResults = getResultsLater()
  63.     println("getResultsLater() returned")
  64.     laterResults.onComplete {
  65.       case Success(result) => println(s"This will only be executed once the future has succeeded: $result")
  66.       case Failure(problem) => println(s"Desaster! ${problem.getMessage}")
  67.     }
  68.  
  69.     val immediateResults = getImmediateResults()
  70.     println("getResultsLater() returned")
  71.     immediateResults.onComplete {
  72.       case Success(result) => println(s"$result")
  73.       case Failure(problem) => println(s"This should never happen.. ;-) If it does, here's why: ${problem.getMessage}")
  74.     }
  75.  
  76.   }
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement