Wait until all Future.onComplete callbacks are executed

后端 未结 2 1802
萌比男神i
萌比男神i 2021-01-05 04:25

I am using the Future API from Scala 2.10.X.

Here is my use case:

object Class1 {

  def apply(f: (Int) => Future[String])(i: Int): F         


        
2条回答
  •  走了就别回头了
    2021-01-05 05:09

    With 1 Future and 3 onComplete

    I think you're going to have to go the route of either composing your functions into a single onComplete call or else you'll have to do exactly what you said, use map:

     val fut1 = myFut map func1 // yes, a Future[Unit]
     val fut2 = myFut map func2
     val fut3 = myFut map func3
    

    Follow the next section to find out when they all finish.

    With 3 different Futures

    It's very possible to know when all three Futures will complete. In fact, in Scala Future composes!

     def threeFutures(one: Future[Int], two: Future[Int], three: Future[Int]) {
       val fourth = for {
         _ <- one
         _ <- two
         _ <- three
       } yield 0
    
       fourth onComplete {
         case _ => println("all done")
       }
     }
    

    Now what does this mean? It means that fourth is a Future which does not care about the inputs of the three arguments but that, when they all are complete, it will complete itself. This is pre-packaged and made ready just for you.

    (Side note: In the example I'm also assuming you have all your implicits in scope.)

提交回复
热议问题