Futures / Success race

后端 未结 3 1684
遥遥无期
遥遥无期 2020-12-04 01:45

I\'m learning futures, and I\'m trying to create a method that, take two futures as parameter (f and g) and return the first future that was succes

3条回答
  •  北海茫月
    2020-12-04 02:40

    I completely agree with the previous answer, still i hope my example will clarify it a bit further, so:

    def successRace[T](f: Future[T], g: Future[T]): Future[T] = {
      val promise = Promise[T]()
    
      f onComplete(promise.tryComplete(_))
      g onComplete(promise.tryComplete(_))
    
      promise.future
    }
    

    so the first completed Future will set the value wrapped in Try (so, Success or Failure).

提交回复
热议问题