How are Scala Futures chained together with flatMap?

前端 未结 3 750
孤独总比滥情好
孤独总比滥情好 2021-02-08 18:10

I\'m working on using Futures for the first time in Scala and am working through an example of using the flatMap combinator; I\'ve been following this discussion:

http:/

3条回答
  •  Happy的楠姐
    2021-02-08 18:57

    You also have a good example of concurrent Future execution in "Scala notes – Futures – 3 (Combinators and Async)" from Arun Manivannan.

    Our Futures need to run in parallel.
    In order to achieve this, all we need to do is to extract the Future block out and declare them separately.

    Code:

    val oneFuture: Future[Int] = Future {
      Thread.sleep(1000)
      1
    }
    
    val twoFuture: Future[Int] = Future {
      Thread.sleep(2000)
      2
    }
    
    val threeFuture: Future[Int] = Future {
      Thread.sleep(3000)
      3
    }
    

    for-comprehension:

    def sumOfThreeNumbersParallelMapForComprehension(): Future[Int] = for {  
        oneValue <- oneFuture
        twoValue <- twoFuture
        threeValue <- threeFuture
    } yield oneValue + twoValue + threeValue
    

    flatmap:

    def sumOfThreeNumbersParallelMap(): Future[Int] = oneFuture.flatMap { oneValue =>  
        twoFuture.flatMap { twoValue =>
          threeFuture.map { threeValue =>
            oneValue + twoValue + threeValue
          }
        }
    }
    

    Test:

    describe("Futures that are executed in parallel") {
      it("could be composed using for comprehensions") {
        val futureCombinators = new FutureCombinators
        val result = timed(Await.result(futureCombinators.sumOfThreeNumbersParallel(), 4 seconds))
          result shouldBe 6
      }
    }
    

    It does illustrate that:

    1. Future is a container of a value(s) of some type (i.e it accepts a type as an argument and it can’t exist without it).
      You can have a Future[Int] or Future[String] or Future[AwesomeClass] – you can’t just have a plain Future.
      A fancy term for this is type-constructor.
      To compare, a List is a type constructor (and a Monad as well).
      A List is a container of values that are of type Int, String or any of other types. A List/Future without a contained type does not exist.
    2. Future has flatMap and unit functions (and consequentially a map function too).

提交回复
热议问题