Skip to content

Instantly share code, notes, and snippets.

@amuradyan
Created April 23, 2022 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amuradyan/323e30103085112949ff03d898dd9044 to your computer and use it in GitHub Desktop.
Save amuradyan/323e30103085112949ff03d898dd9044 to your computer and use it in GitHub Desktop.
Controllable Futures
// 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