Scala Futures in For Comprehension -
i'm trying wrap head around scala , i'm wondering following does:
val ffuture: future[int] = future { println("f called"); 3 } val gfuture: future[int] = future { println("g called"); 4 } { f <- ffuture g <- gfuture } yield f
the futures executed inside of comprehension, correct? f
in yield statement? mean it's available? considered return value
if inside of function?
the futures starting execute here:
val ffuture: future[int] = future { println("f called"); 3 } val gfuture: future[int] = future { println("g called"); 4 }
so both executions starting in parallel. if accidentally put future{...}
inside for-comprehension - gonna executed sequentially.
for-comprehension subscribes , merges 2 results 1 future. however, in case seems second future's result ignored, doesn't makes sense. code makes sense:
for { f <- ffuture g <- gfuture } yield f + g
this code returns future[int]
(same code in example). if extract value future - 3 + 4 = 7
. it's still not best approach computations independent , probability of developer's mistake (stated above) makes them sequential still high, recommended approach independent computations is:
(ffuture zip gfuture) map { case (f, g) => f + g }
this code referentially transparent in meaning if replace ffuture
future{...}
- still behaves same (in case of future
-they're going executed in prallel, might different other concurrency primitives)
where for-comprehension
make sense? here:
for { f <- future{... 9} g <- if (f > 0) future{...} else future{...} } yield g
as g
depends on f
here - there no way run in parallel, for
provides non-blocking way of composing several future
s
Comments
Post a Comment