Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Values initialized from a chain of futures

Tags:

scala

future

Consider a following snippet of code:

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 perform such an initialization but using vals instead of vars (somehow)? The point is, I don't want to block and wait for every intermediate result, just for the last one.

like image 780
Sergey Weiss Avatar asked Jan 17 '23 02:01

Sergey Weiss


2 Answers

Unless you have 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
like image 169
Debilski Avatar answered Jan 21 '23 03:01

Debilski


Could you delay the result evaluation by using lazy values ? Something like:

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 at initialisation without blocking, but you will block the first time you actually try to use a result.

like image 44
paradigmatic Avatar answered Jan 21 '23 03:01

paradigmatic