Accessing value returned by scala futures

后端 未结 6 688
野趣味
野趣味 2020-12-01 01:54

I am a newbie to scala futures and I have a doubt regarding the return value of scala futures.

So, generally syntax for a scala future is

 def downl         


        
6条回答
  •  失恋的感觉
    2020-12-01 02:31

    It wasn't yet mentioned, so I want to emphasize the point of using Future with for-comprehension and the difference of sequential and parallel execution.

    For example, for sequential execution:

    object FuturesSequential extends App {
    
      def job(n: Int) = Future {
        Thread.sleep(1000)
        println(s"Job $n")
      }
    
      val f = for {
        f1 <- job(1)
        f2 <- job(2)
        f3 <- job(3)
        f4 <- job(4)
        f5 <- job(5)
      } yield List(f1, f2, f3, f4, f5)
      f.map(res => println(s"Done. ${res.size} jobs run"))
      Thread.sleep(6000) // We need to prevent main thread from quitting too early
    }
    

    And for parallel execution (note that the Future are before the for-comprehension):

    object FuturesParallel extends App {
    
      def job(n: Int) = Future {
        Thread.sleep(1000)
        println(s"Job $n")
      }
    
      val j1 = job(1)
      val j2 = job(2)
      val j3 = job(3)
      val j4 = job(4)
      val j5 = job(5)
    
      val f = for {
        f1 <- j1
        f2 <- j2
        f3 <- j3
        f4 <- j4
        f5 <- j5
      } yield List(f1, f2, f3, f4, f5)
      f.map(res => println(s"Done. ${res.size} jobs run"))
      Thread.sleep(6000) // We need to prevent main thread from quitting too early
    }
    

提交回复
热议问题