Created
April 23, 2022 23:24
-
-
Save amuradyan/323e30103085112949ff03d898dd9044 to your computer and use it in GitHub Desktop.
Controllable Futures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How to Write Controllable Futures in Scala | Rock the JVM | |
// https://www.youtube.com/watch?v=72kurKY7fX8 | |
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.Promise | |
val aFuture = Future { | |
42 | |
} | |
// an asyncronous service | |
object Service { | |
def produceValue(v: Int): String = "The meaning of life is " + v | |
// shitty executor | |
def submitTask[A](arg: A)(task: A => Unit): Unit = { | |
task(arg) | |
} | |
} | |
def getAValue(arg: Int): Future[String] = { | |
val p = Promise[String]() | |
Service.submitTask(arg) { (v: Int) => | |
val result = Service.produceValue(v) | |
p.success(result) | |
} | |
p.future | |
} | |
val aValue = getAValue(42).map(_ + "!!!") | |
// Promises | |
val p = Promise[String]() | |
val f = p.future | |
def asyncCall(p: Promise[String]) = { | |
p.success("Hello") | |
} | |
asyncCall(p) | |
// use the future | |
val f2 = f.map { x => x + "!!!" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment