Re-tried Future Not Completing

时间:2015-12-04 21:20:04

标签: scala

Given this function, which retries an unevaluated Future n times:

scala>   def retry[A](x: Function0[Future[A]], n: Int): Future[A] = {
     |     if(n <= 0)
     |       x()
     |     else
     |       println("n" + n)
     |       x().recoverWith({ case _ => retry(x, n - 1) })
     |   }
retry: [A](x: () => scala.concurrent.Future[A], n: Int)scala.concurrent.Future[A]

I wrote a test method, g:

scala> def g: Function0[Future[Int]] = () => Future ( throw new RuntimeException("foo") )
g: () => scala.concurrent.Future[Int]

Then, I called retry(g, 5):

scala> retry[Int](g, 5)
n5
n4
res25: scala.concurrent.Future[Int] = Future(<not completed>)
n3
n2
n1

After getting this output, I waited 2 minutes, but the Future isn't showing up as having completed:

scala> res25
res28: scala.concurrent.Future[Int] = Future(<not completed>)

scala> res25.value
res29: Option[scala.util.Try[Int]] = None

What's that about?

1 个答案:

答案 0 :(得分:3)

TLDR :请始终使用if else个括号括号。

你的if声明具有误导性,这里的括号是什么样的:

  def retry[A](x: Function0[Future[A]], n: Int): Future[A] = {
         if (n <= 0) {
           println("n" + n) //added this for clarity
           x()
         } else {
           println("n" + n)
         }
         x().recoverWith({ case _ => retry(x, n - 1) })
       }

基本上,您永远不会达到最终状态,只需继续递增n然后返回x().recoverWith({ case _ => retry(x, n - 1) })

你真正想要的是:

  def retry[A](x: Function0[Future[A]], n: Int): Future[A] = {
         if (n <= 0) {
           println("n" + n)
           x()
         } else {
           println("n" + n)
           x().recoverWith({ case _ => retry(x, n - 1) })
         }
       }