Skip to content

Commit 792b517

Browse files
author
Matteo Di Pirro
committed
SCALA-463 Add code for scala-await article
1 parent e2ecee2 commit 792b517

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.baeldung.scala.async
2+
3+
import org.scalatest.concurrent.ScalaFutures
4+
import org.scalatest.matchers.should.Matchers
5+
import org.scalatest.time.{Millis, Seconds, Span}
6+
import org.scalatest.wordspec.AnyWordSpec
7+
8+
import scala.async.Async.{async, await}
9+
import scala.concurrent.Future
10+
11+
object ScalaAsyncTest {
12+
import scala.concurrent.ExecutionContext.Implicits.global
13+
14+
def slowComputation: Future[Int] = Future {
15+
Thread.sleep(1000)
16+
10
17+
}
18+
19+
def anotherSlowComputation(s: String): Future[Int] = Future {
20+
Thread.sleep(1500)
21+
s.length
22+
}
23+
24+
def sequentialCombination: Future[Int] = async {
25+
await(slowComputation) + await(anotherSlowComputation("Baeldung"))
26+
}
27+
28+
def parallelCombination: Future[Int] = async {
29+
val r1 = slowComputation
30+
val r2 = anotherSlowComputation("Baeldung")
31+
await(r1) + await(r2)
32+
}
33+
34+
/*def invalid = async {
35+
def localFunction = {
36+
await(slowComputation)
37+
}
38+
39+
localFunction
40+
}
41+
42+
def tryCatch = async {
43+
try {
44+
await(slowComputation)
45+
} catch {
46+
case e: Throwable => println(e.getMessage)
47+
}
48+
}*/
49+
50+
def withFor: Future[Int] = for {
51+
r1 <- slowComputation
52+
r2 <- anotherSlowComputation("Baeldung")
53+
} yield r1 + r2
54+
}
55+
56+
class ScalaAsyncTest extends AnyWordSpec with Matchers with ScalaFutures {
57+
58+
import ScalaAsyncTest._
59+
60+
implicit private val defaultPatience: PatienceConfig =
61+
PatienceConfig(timeout = Span(3, Seconds), interval = Span(500, Millis))
62+
63+
"Futures combination" should {
64+
"work sequentially" in {
65+
whenReady(sequentialCombination) { r =>
66+
assert(r == 18)
67+
}
68+
}
69+
70+
"work in parallel" in {
71+
whenReady(parallelCombination) { r =>
72+
assert(r == 18)
73+
}
74+
}
75+
76+
"give the same result as Futures composed with for comprehension" in {
77+
whenReady(withFor) { r =>
78+
assert(r == 18)
79+
}
80+
}
81+
}
82+
}

0 commit comments

Comments
 (0)