Initialized from the Futures Chain

Consider the following code snippet:

class MyClass { var a = _ var b = _ ... var y = _ val z = (for { a0 <- someMethodReturningFuture b0 <- someMethodReturningFuture(a0) ... z0 <- someMethodReturningFuture(y0) } yield { a = a0 b = b0 ... y = y0 someCalculation(y) }).result } 

Is it possible to do this initialization, but using val instead of var (somehow)? The fact is that I do not want to block and wait for each intermediate result, only for the latter.

+4
source share
2 answers

If you have no more than 22 variables:

 val (a, b, c, d, ..., v) = (for { a0 <- someMethodReturningFuture b0 <- someMethodReturningFuture(a0) ... u0 <- someMethodReturningFuture(t0) } yield { (a0, b0, ..., u0, someCalculation(u0)) }).result 
+6
source

Is it possible to delay evaluation of result using lazy values? Sort of:

 class MyClass { lazy val a = myFutures.a.result lazy val b = myFutures.b.result private val myFutures = new AnyRef { val a = someMethodReturningFuture val b = a.map( a0 => someMethodReturningFuture(a0) ) } } 

All futures are created during initialization without blocking, but you will block the first time you really try to use the result.

+3
source

All Articles