Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.concurrent.{Future, Promise}
- import scala.util.{Failure, Random, Success}
- import scala.concurrent.ExecutionContext.Implicits.global
- object FutureTest {
- /** This immitates the BaseRecognizeCallback that you have. */
- trait BaseRecognizeCallback {
- def onTranscription(result: String): Unit
- def onFailure(exception: Throwable): Unit
- }
- /**
- * A function that computes the result asynchronously and informs the calling code through
- * a callback. In your case, this would be this 'recognizeUsingWebSocket'.
- * @param callback the function that will be called, when the result is available.
- */
- def recognizeUsingWebSocket(callback: BaseRecognizeCallback): Unit = {
- new Thread(() => {
- val randomSeconds = new Random().nextInt(5)
- println(s"Waiting randomly for $randomSeconds seconds")
- Thread.sleep(randomSeconds * 1000L)
- if (randomSeconds % 2 == 0) {
- callback.onFailure(new RuntimeException(s"Randomly Failed after $randomSeconds seconds"))
- } else {
- callback.onTranscription("Complete Success!")
- }
- }).start()
- }
- def getResultsLater(): Future[String] = {
- val maybeSolution = Promise[String]()
- val cb = new BaseRecognizeCallback {
- override def onTranscription(result: String): Unit =
- maybeSolution.complete(Success(result))
- override def onFailure(exception: Throwable): Unit =
- maybeSolution.complete(Failure(new RuntimeException("Error while doing complicated work!", exception)))
- }
- // now tell our asynchronous computation to compute the result
- recognizeUsingWebSocket(cb)
- // return the future result
- maybeSolution.future
- }
- /**
- * Just to make the example complete, here's the case where we don't have to wait.
- * @return future results.
- */
- def getImmediateResults(): Future[String] = {
- Future("This was quick!")
- }
- def main(args: Array[String]): Unit = {
- val laterResults = getResultsLater()
- println("getResultsLater() returned")
- laterResults.onComplete {
- case Success(result) => println(s"This will only be executed once the future has succeeded: $result")
- case Failure(problem) => println(s"Desaster! ${problem.getMessage}")
- }
- val immediateResults = getImmediateResults()
- println("getResultsLater() returned")
- immediateResults.onComplete {
- case Success(result) => println(s"$result")
- case Failure(problem) => println(s"This should never happen.. ;-) If it does, here's why: ${problem.getMessage}")
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement