|
| 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 | + /* Uncommenting this snippet will produce the following error: |
| 35 | + await must not be used under a nested method. await(slowComputation) |
| 36 | +
|
| 37 | + def invalid = async { |
| 38 | + def localFunction = { |
| 39 | + await(slowComputation) |
| 40 | + } |
| 41 | +
|
| 42 | + localFunction |
| 43 | + }*/ |
| 44 | + |
| 45 | + /* Uncommenting this snippet will produce the following error: |
| 46 | + await must not be used under a try/catch. await(slowComputation) |
| 47 | +
|
| 48 | + def tryCatch = async { |
| 49 | + try { |
| 50 | + await(slowComputation) |
| 51 | + } catch { |
| 52 | + case e: Throwable => println(e.getMessage) |
| 53 | + } |
| 54 | + }*/ |
| 55 | + |
| 56 | + def withFor: Future[Int] = for { |
| 57 | + r1 <- slowComputation |
| 58 | + r2 <- anotherSlowComputation("Baeldung") |
| 59 | + } yield r1 + r2 |
| 60 | +} |
| 61 | + |
| 62 | +class ScalaAsyncTest extends AnyWordSpec with Matchers with ScalaFutures { |
| 63 | + |
| 64 | + import ScalaAsyncTest._ |
| 65 | + |
| 66 | + implicit private val defaultPatience: PatienceConfig = |
| 67 | + PatienceConfig(timeout = Span(3, Seconds), interval = Span(500, Millis)) |
| 68 | + |
| 69 | + "Futures combination" should { |
| 70 | + "work sequentially" in { |
| 71 | + whenReady(sequentialCombination) { r => |
| 72 | + assert(r == 18) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + "work in parallel" in { |
| 77 | + whenReady(parallelCombination) { r => |
| 78 | + assert(r == 18) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + "give the same result as Futures composed with for comprehension" in { |
| 83 | + whenReady(withFor) { r => |
| 84 | + assert(r == 18) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments