Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Future without starting it

This is a follow-up to my previous question

Suppose I want to create a future with my function but don't want to start it immediately (i.e. I do not want to call val f = Future { ... // my function}.

Now I see it can be done as follows:

val p = promise[Unit]
val f = p.future map { _ => // my function here }

Is it the only way to create a future with my function w/o executing it?

like image 714
Michael Avatar asked May 15 '13 20:05

Michael


2 Answers

You can do something like this

val p = Promise[Unit]()
val f = p.future

//... some code run at a later time
p.success {
// your function
}

LATER EDIT:

I think the pattern you're looking for can be encapsulated like this:

class LatentComputation[T](f: => T) {
  private val p = Promise[T]()

  def trigger() { p.success(f) }

  def future: Future[T] = p.future
}

object LatentComputation {
  def apply[T](f: => T) = new LatentComputation(f)
}

You would use it like this:

val comp = LatentComputation {
// your code to be executed later
}

val f = comp.future

// somewhere else in the code
comp.trigger()
like image 158
Marius Danila Avatar answered Sep 28 '22 17:09

Marius Danila


You could always defer creation with a closure, you'll not get the future object right ahead, but you get a handle to call later.

type DeferredComputation[T,R] = T => Future[R]

def deferredCall[T,R](futureBody: T => R): DeferredComputation[T,R] =
  t => future {futureBody(t)}

def deferredResult[R](futureBody: => R): DeferredComputation[Unit,R] =
  _ => future {futureBody}
like image 23
pagoda_5b Avatar answered Sep 28 '22 15:09

pagoda_5b