Scala's “for comprehension” with futures

后端 未结 3 1489
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 02:46

I am reading through the Scala Cookbook (http://shop.oreilly.com/product/0636920026914.do)

There is an example related to Future use that involves for comprehension.

3条回答
  •  野性不改
    2020-11-28 03:07

    To elaborate those existing answers here a simple result to demonstrate how for comprehension works.

    Its bit lengthy functions yet they worth taking look into it.

    A function that give us a range of integers

    scala> def createIntegers = Future{
                 println("INT "+ Thread.currentThread().getName+" Begin.")
                 val returnValue = List.range(1, 256)
                 println("INT "+ Thread.currentThread().getName+" End.")
                 returnValue
             }
    createIntegers: createIntegers: scala.concurrent.Future[List[Int]]
    

    A function that give us a range of chars

    scala> def createAsciiChars = Future{
                 println("CHAR "+ Thread.currentThread().getName+" Begin.")
                 val returnValue = new ListBuffer[Char]
                 for (i <- 1 to 256){
                      returnValue += i.toChar
                 }
                 println("CHAR "+ Thread.currentThread().getName+" End.")
                 returnValue
              }
    createAsciiChars: scala.concurrent.Future[scala.collection.mutable.ListBuffer[Char]]
    

    Using these function calls within the for comprehension.

    scala> val result = for{
                            i <- createIntegers
                            s <- createAsciiChars
                        } yield i.zip(s)
           Await.result(result, Duration.Inf)
    result: scala.concurrent.Future[List[(Int, Char)]] = Future()
    

    For these below lines we can make out that all the function calls are synchronous i.e. createAsciiChars function call is not executed until createIntegers completes its execution.

    scala> INT scala-execution-context-global-27 Begin.
           INT scala-execution-context-global-27 End.
           CHAR scala-execution-context-global-28 Begin.
           CHAR scala-execution-context-global-28 End.
    

    Making these function createAsciiChars, createIntegers calls outside the for comprehensions will be asynchronous execution.

提交回复
热议问题