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 val
s instead of var
s (somehow)? The point is, I don't want to block and wait for every intermediate result, just for the last one.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With